Answer the question
In order to leave comments, you need to log in
Chicken or egg? How to create a record in one of two tables linked to each other by foreign keys?
Suppose there are two tables - one is tied to the other with foreign keys, and in order to create a record in one of the tables, you need to enter a valid key for the other. But in the other there is no such key, for obvious reasons - because in order to create it, you need to create the necessary foreign key in the first one. And so on ad infinitum.
Laravel swears and does not allow creating records in tables in the absence of a valid foreign key, and this is understandable. Other programs for working with the database also swear. And I'm confused.
Update: Apparently yes, somewhere there is an extra connection and I did not fully understand the principle. Here is a model for Laravel I came up with:
And this is how, apparently crookedly, I implemented the creation of links for tables in migrations (postals is a table with data about the address of the order, they are tied exclusively to product1s and product2s when they are ordered):
Schema::table('payments', function ($table) {
$table->foreign('user_id')->references('id')->on('users');
$table->foreign('product1_id')->references('id')->on('product1s');
$table->foreign('product2_id')->references('id')->on('product2s');
});
Schema::table('product1s', function ($table) {
$table->foreign('user_id')->references('id')->on('users');
$table->foreign('postal_id')->references('id')->on('postals');
$table->foreign('payment_id')->references('id')->on('payments');
});
Schema::table('product2s', function ($table) {
$table->foreign('user_id')->references('id')->on('users');
$table->foreign('postal_id')->references('id')->on('postals');
$table->foreign('payment_id')->references('id')->on('payments');
});
Schema::table('postals', function ($table) {
$table->foreign('product1_id')->references('id')->on('product1s');
$table->foreign('product2_id')->references('id')->on('product2s');
});
Answer the question
In order to leave comments, you need to log in
I correctly understood why this might be needed - is it a bunch of MANY-MANY?
If so, throw away the double bind and preferably don't do it. Instead, use an additional table for the link. For example: there are 2 tables users[id, name] AND groups[id, name]. For them, create another groupsHasUsers[groupId, userId].
There is something wrong with your database architecture....describe the problem in a less abstract way. Who is connected with whom and how did it happen that you have such a crooked base structure?
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question