Answer the question
In order to leave comments, you need to log in
How to deal with foreign keys muscle?
There is a table of users, there is a table of orders, I decided to link them by a foreign key, there are many orders for one user.
added a foreign key to the orders table. Now I need to know this. Foreign key ID (user ID in the table of orders) we will set, roughly speaking, manually through a variable in the request, right?
Answer the question
In order to leave comments, you need to log in
Do you need something different? You have a logged in user, you keep his id somewhere. Now, when a logged in user places an order, you add a new order to that user by specifying a specific user_id when inserting a record into the orders table.
The meaning of the foreign key is that the DBMS will not allow you to add an order for a non-existent user. Those. when inserting, a check will automatically occur that there is a record in the parent table of users with the id that you specified in the order being added.
You can do such an insert without a foreign key, you don't have to use foreign keys at all - anyway, you will do all the necessary selections yourself. Foreign keys are just one of the types of integrity constraints, roughly speaking add. verification by the DBMS so that you can feel more relaxed about the consistency of the database (you don’t really want to have a “hanging” order added to you in the event of some annoying error in the application, it’s not clear who at all). Well, they also allow you to perform some cascading operations, for example, delete all orders when deleting a user - if of course you allow it to do so.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question