nazmun
September 11, 2022, 8:36am
1
Hello, I am new to Laravel. I know I can use a migration to create a table. But I am having a hard time adding foreign keys and constraints.
I have a users table and I want the user id will be a foreign key in the posts table.
Schema::create('posts', function(Blueprint $table) {
$table->increments('id');
$table->bigInteger('user_id')->unsigned();
$table->string('title', 255);
$table->longText('content');
$table->timestamps();
});
What’s the best way to add a foreign key?
You have to make your user_id
field an index:
$table->index('user_id');
Create a foreign key with constraint
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
Your migration should look like this
Schema::create('posts', function(Blueprint $table) {
$table->increments('id');
$table->bigInteger('user_id')->unsigned();
$table->string('title', 255);
$table->longText('content');
$table->timestamps();
$table->index('user_id');
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
});
In your down() function, you have to add those lines.
$table->dropForeign('lists_user_id_foreign');
$table->dropIndex('lists_user_id_index');
$table->dropColumn('user_id');
doom
September 11, 2022, 9:02am
3
Why not use this?
$table->dropForeign('user_id);
$table->dropIndex('user_id');