Blueprint foreignIdFor should add foreign key constraint #45707
-
Hey! public function up()
{
Schema::create('products', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->foreignIdFor(\App\Models\Manufacturer::class);
});
} will generate the following table (DDL): create table products
(
id bigint unsigned auto_increment primary key,
name varchar(255) not null,
manufacturer_id bigint unsigned not null
) And now I am wondering, what is the benefit of using public function up()
{
Schema::create('products', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->foreignIdFor(\App\Models\Manufacturer::class)->references("id")->on("manufacturers");
});
} which generates the following DDL: create table products
(
id bigint unsigned auto_increment primary key,
name varchar(255) not null,
manufacturer_id bigint unsigned not null,
constraint products_manufacturer_id_foreign
foreign key (manufacturer_id) references manufacturers (id)
) Looking forward to your replies! |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments 3 replies
-
just adding constrained method can resolve your problem |
Beta Was this translation helpful? Give feedback.
-
The reason that Laravel doesn't automatically add an SQL constraint is that sometimes you don't want one but you want someone reading the migration code to understand that the field is nonetheless a foreign key. But there are several methods of adding a constraint in your migration, including the one mentioned by @anilkumarthakur60, the one you mentioned in your original post and the following:
|
Beta Was this translation helpful? Give feedback.
just adding constrained method can resolve your problem