我不知道出了什么问题,因为我对此很陌生。
// 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');
但仍然无法正常工作。
我想要的是一个关系,这样当我删除一个商店时,属于该商店的所有产品也会被删除。
谢谢?
答案 0 :(得分:2)
将商店迁移文件的名称更改为 2021-07-28 之前的日期,以便表 stores
在表 products
之前迁移
示例:2021_07_27_004700_create_stores_table
Laravel 使用迁移文件的名称作为迁移顺序。以日期的格式作为文件名的开头,它依赖于文件的创建日期。