【问题标题】:Laravel 8 - Foreign key constraint is incorrectly formedLaravel 8 - 外键约束的格式不正确
【发布时间】:2023-03-19 12:31:01
【问题描述】:

我不知道出了什么问题,因为我对此很陌生。

// 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)

标签: laravel eloquent laravel-8


【解决方案1】:

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

例如:2021_07_27_004700_create_stores_table

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

【讨论】:

  • 哇!谢谢,它奏效了!我不知道迁移的顺序很重要。
猜你喜欢
  • 2021-12-30
  • 2017-10-03
  • 2019-07-25
  • 2017-10-04
  • 2018-02-19
  • 2021-05-26
  • 2020-09-24
  • 2019-11-02
  • 2020-04-15
相关资源
最近更新 更多