Reputation:
I am creating a database for to manage companies and their products(category) and customers. I have designed my database but i want to be sure if my table does not foul the rules of database schema.
users table and product table
are linked many to many (having a pivot product_user
).
In that instance,
user 1 can have enter a product called hardware
so in the pivot table, product_id : 1 & user_id : 1
user 2 can also enter the same product called hardware
so in the pivot table, product_id : 2 & user_id : 2
Is it a good way to do this? I am new to laravel now. Please help. Thank you
Upvotes: 0
Views: 671
Reputation: 1982
Beside the fact that this is not a PHP nor a Laravael nor a MySQL (as a product) question, the real question is what should this many to many relationship stands for?
This is all about general database schema design. We can't tell you if this is right or wrong because we don't know what its meant to be.
If you you can build sentences like "A User has/have zero, ore or more Products" and at the same time "A Product is used by/belong to zero, one or more Users" than this is a good indicator that a Many to Many Relationship is required.
But there could be exceptions where the many to many relation ship is more than just a linking table. Because if a user bought a product than this is most likely a litle bit more complex.
e.g. at an online shop a user can do one ore more purchases, but one purchase belongs only to one user. The purchase do include one or more Products, and the a Product can be part of one ore more purchases. And than there is billing and shipping and all the stuff involved. In this case you could do a direct relation between user and products, but what dose it tell you? What if a user buy a product more than once?
There are situations where you could think that a many to many would be a good idea but in fact it is not (see above) because you create redundant data and/or break data integrity. The Process to avoid this is called normalization: https://en.wikipedia.org/wiki/Database_normalization
A good example of an many to many relation ship is User
and Privileges
.
There are users and there are privileges that an user can have. So a user can have zero, one or more Privileges and a privilege can be applied to zero, one or more Users.
So if you ask if product_user
is a good way to do it the real answer is: it depends!
Upvotes: 0
Reputation: 1925
Yes this is a good way, but I would suggest you use "company" instead of "user". This way the naming is clear for everyone.
You might want to read the official documentation of relationships. The examples are also very useful and easy to understand.
Upvotes: 1