Seydina's avatar

Eloquent two key relationship with Product, User, and Category table with two categories only

Hi, here are my migrations files :

and here are my factories files :

The relationship between users and products works fine and with fake data I can do this in Tinker :

  • $users = App\Models\Users::factory(10)->create(); that create 10 users.
  • $products = App\Models\Product::factory()->count(20)->recycle($users)->create(); that create 20 products shared randomly between 10 users. But what I see is the products table is displayed like this :
products
+----+------------+----------------+--------------+-------------+
| id | name       | category_id | user_id | ...
+----+------------+-----------------+----------+-------------+
| 1  | Polo Z     | 1                    |         5       | ...      |
| 2  | T-sh100  | 2                    |         8       | ...      |
| 3  | Nike D     | 3                    |         4       | ...      | 
| 4  | Sport D   | 4                    |         1       | ...      |
...    ...               ...             ...   
+----+------------+-------------+-------+---------------------+ 				

and the categories table is like this :

categories
+----+------------+-------------+-------+
| id | name       | slug          |  ...
+----+------------+-------------+-------+
| 1  | Shirts       | shirts              |    
| 2  | Shoes       | shoes                 |         
+----+------------+-------------+-------+				

The category_id increment by 1, 2, 3, 4... in products table instead of alternating between id 1 or 2. What I want it is to display it like this :

products
+----+------------+-------------+-------+-------------+
| id | name       | category_id | user_id | ...
+----+------------+-------------+-------+-------------+
| 1  | Nike D      | 2               |         5       | 
| 2  | T-H100     | 1               |         8       |
| 3  | Sport R     | 2               |         4       | 
| 4  | Polo Z       | 1               |         1       |
...    ...               ...             ...   
+----+------------+-------------+-------+-------------+ 				

What I missed in my schema design?

0 likes
0 replies

Please or to participate in this conversation.