Laravel 8-外键约束格式不正确 [英] Laravel 8 - Foreign key constraint is incorrectly formed
本文介绍了Laravel 8-外键约束格式不正确的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我不知道出了什么问题,因为我对此还很陌生。
// Product Model
class Product extends Model
{
use HasFactory;
public function store()
{
return $this->belongsTo(Store::class);
}
}
// Store Model
class Store extends Model
{
use HasFactory;
public function products()
{
return $this->hasMany(Product::class);
}
}
// Products table migration
Schema::create('products', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->float('price');
$table->string('description');
$table->timestamps();
$table->foreignId('store_id')->constrained()->onDelete('cascade');
});
// Stores table migration
Schema::create('stores', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('image_url');
$table->string('phone');
$table->timestamps();
});
当我运行迁移时,会出现以下错误
我已尝试更改‘id’的数据类型,但仍不起作用。我也试过
$table->foreign('store_id')->references('id')->on('stores')->onDelete('cascade');
但仍不起作用。
我需要的是一个关系,这样当我删除商店时,属于该商店的所有产品也会被删除。
谢谢🙏
推荐答案
将存储迁移文件的名称更改为2021-07-28之前的日期,以便表stores
在表products
示例:2021_07_27_004700_create_stores_table
Laravel使用迁移文件的名称作为迁移顺序。以日期的格式作为文件名的开始,它取决于文件的创建日期。
这篇关于Laravel 8-外键约束格式不正确的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文