【发布时间】: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