我正在尝试创建与customer
和shop
链接的many-to-many
在 laravel 中,但(errno: 150 "Foreign key constraint is incorrectly formed")
卡在此错误中,但仍然没有弄清楚。
这是我customers
表
Schema::create('customers', function (Blueprint $table) {
$table->bigIncrements('id');
$table->unsignedBigInteger('shop_id');
$table->string('name');
$table->string('email');
$table->string('phone');
$table->timestamps();
$table->foreign('shop_id')->references('id')->on('shop');
});
这是我shops
桌
Schema::create('shops', function (Blueprint $table) {
$table->bigIncrements('id');
$table->unsignedBigInteger('customer_id');
$table->string('name');
$table->timestamps();
$table->foreign('customer_id')->references('id')->on('customer');
});
我的Shop
模型
protected $fillable = ['name'];
public function customer()
{
return $this->belongsToMany(AppCustomer::class);
}
我的Customer
模型
protected $fillable = ['name', 'email', 'phone'];
public function shop()
{
return $this->belongsToMany(AppShop::class);
}
有什么帮助吗?提前感谢....
检查您的架构 - 它应该是商店而不是商店...
$table->foreign('shop_id')->references('id')->on('shops');
同样,客户不是客户...
$table->foreign('customer_id')->references('id')->on('customers');
请注意。不要在表创建命令中一起使用外部命令。
确保始终使用新的迁移文件来添加表内的外键。
导致有时它在迁移时生成错误.. 打开你的 bash shell 或 PHP 风暴终端或 CMD
php artisan make:migration foreign_customer_id_at_table_shops --table=shops //you Can use your own migration name what you want
在迁移文件中foreign_customer_id_at_table_shops
向上
$table->foreign('customer_id')->references('id')->on('customers');
下
$table->dropForeign(['customer_id']);
将外键放在关系中,而不是在迁移中。
public function customer()
{
return $this->belongsToMany('AppCustomer::class','id','shop_id');
}
public function shop()
{
return $this->belongsToMany('AppShop::class','id','customer_id');
}
多对多的关系需要第三个表pivot
你错过的表。
这样做会创建新的迁移。php artisan make:migration create_customer_shop
无需为数据透视表
创建模型
然后你 架构数据透视表 像这样的东西。
数据透视表
Schema::create('cutomer_shop', function (Blueprint $table) {
$table->increments('id');
$table->integer('customer_id')->unsigned();
$table->integer('shop_id')->unsigned();
$table->timestamps();
$table->foreign('customer_id')->references('id')->on('customers');
$table->foreign('shop_id')->references('id')->on('shops');
});
两个表shops
和customers
没有任何直接关系,它们仅通过数据透视表建立关系。
注意:确保所有三个表ID类型increments('id')
和所有外键都$table->integer('shop_id')->unsigned();
否则会给出不正确的格式错误。