There a able, called 'interests' which hold the id(s) of 'categories' and/or 'brands' that each user has interest in.
To prevent creating two separate tables for user_category_interests
and user_brand_interest
I added an enum column called type
.
Now I can't figure out how should I create a migration in Schema Builder, How to set relations and foreign keys,... to take advantage of using Eloquent methods.
Schema::create('user_interests', function (Blueprint $table) {
$table->increments('id');
$table->enum('type', ['categories', 'brands']);
$table->integer('reference_id')->unsigned();
$table->timestamps();
});
Is there any better way instead of creating two separate tables and models?
P.S. I use laravel 5.4
Brands Table:
id | name
-----------
1 | Adidas
2 | Nike
3 | Puma
Categories Table:
id | name
-----------
1 | Clothes
2 | Luxury
3 | Sport Wear
User_Interests Table:
id | user_id | type | reference_id
-----------------------------------------
1 | 113 | 'brand' | 2
1 | 113 | 'brand' | 3
2 | 113 |'category'| 3
3 | 224 | 'brand' | 1
Yes - read the docs on polymorphic relations.
It works similar to what you have, but you might have columns called interestable_id
and interestable_type
(you can configure this to something else if you prefer). The interestable_type
will literally be the string representation of the referenced class name, like App\Brand
or App\Category
and interestable_id
will be the primary key of that model.
Best part is as it's all done through Eloquent it's already good to go with associations, eager-loading etc.
Edit: I should add that your 3 table setup is still the best way to represent this structure, just making suggestions on the column names you use and how to hook it in with Eloquent.