The Problem
I want to add foreign keys to tables. When I run my first migration create_posts_table that looks like this:
Schema::create('posts', function(Blueprint $table) {
$table->engine = 'InnoDB';
$table->increments('id');
$table->unsignedInteger('user_id')->index();
// . . .
});
Schema::table('posts', function(Blueprint $table)
{
$table->foreign('user_id')->references('id')
->on('users')->onDelete('cascade');
});
The following error is thrown:
[Illuminate\Database\QueryException] SQLSTATE[HY000]:
General error: 1215 Cannot add foreign key constraint (SQL: alter table
usersadd constraintusers_institution_id_foreignforeign key (institution_id) referencesinstitutions(id) on delete cascade)
This is caused because the users table is not created yet, hence the failure to create the users' referencing foreign key on the posts table.
Possible Solution
The solution to this problem would be to add the foreign keys after all of the tables had been created with a new migration. However, it seems clunky to me.
The question
How can I define the foreign keys inside their respective tables' migrations, instead of adding them separately with the different migration after all of the tables had been created?
from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1t85VGs
via IFTTT
Aucun commentaire:
Enregistrer un commentaire