@Aetrox I’d say you have users that have many devices, and a device has many attributes. An attribute would be key–value pairs for things like colour, storage capacity etc. Serial number sounds pretty standard, so I’d be tempted to move that to the Device model.
Relations
Hello,
after the 7th time deleting my tables and models, i realize i need a bit of help getting my database structure working.
I have a User with multiple Devices.
Each Device has data like Serialnumber, purchase date and so on.
Each Device has a related table Storage, Color, Model, Manufacturer.
So what relations do i have?
User hasMany Devices
Device hasOne Color Device hasOne Storage Device hasOne Model Device hasOne Manufacturer
where do i have to set the foreignkeys now?
Do i have a table with devices with a foreignkey user_id? And do i have a table Storage with a foreignkey device_id?
I am not sure about this because after my logic i then have a table like: Storage | device_id 256 | 1 256 | 2 64 | 3
Am i on the right track or would there be a better solution?
At the end i just want to find a user and get all device-data without having to write 20 loops and 40 lines of code.
RIght now i have a many to many between user and device and in my device table i have foreignkeys for storage color model and manufacturer but if i do it like in the docs i should have the foreignkeys on the Device-Data-Tables to access them with a hasOne Relation.
I hope i didnt wrote to much senseless stuff.
I would be happy if you could help me out a little bit.
Thanks a lot.
@Aetrox A device would have many attributes, so that means your attributes table would have a device_id foreign key:
Schema::create('devices', function (Blueprint $table) {
$table->increments('id');
$table->string('serial_number')->unique();
$table->timestamps();
});
Schema::create('attributes', function (Blueprint $table) {
$table->increments('id');
$table->unsignedInteger('device_id');
$table->string('name');
$table->string('value');
$table->timestamps();
$table->foreign('device_id')->references('id')->on('devices')->onDelete('cascade');
// Stops a single device having multiple attributes with the same name
$table->unique(['device_id', 'name']);
});
Please or to participate in this conversation.