Laravel 8 - 外键约束的格式不正确

时间:2021-07-28 14:28:29

标签: laravel eloquent 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();
});

当我运行迁移时,它给了我这个错误 The error

我已尝试更改“id”的数据类型,但仍然无法正常工作。我也试过

$table->foreign('store_id')->references('id')->on('stores')->onDelete('cascade');

但仍然无法正常工作。

我想要的是一个关系,这样当我删除一个商店时,属于该商店的所有产品也会被删除。

谢谢?

1 个答案:

答案 0 :(得分:2)

将商店迁移文件的名称更改为 2021-07-28 之前的日期,以便表 stores 在表 products 之前迁移

示例:2021_07_27_004700_create_stores_table

Laravel 使用迁移文件的名称作为迁移顺序。以日期的格式作为文件名的开头,它依赖于文件的创建日期。

相关问题