迁移:无法添加外键约束-Laravel 9



我正试图在Laravel中创建外键,但当我使用artisan迁移表时,我遇到了以下错误:

SQLSTATE[HY000]: General error: 1005 Can't create table `bright`.`carts` (errno: 150 "Foreign key constraint is incorrectly formed") (SQL: alter table `carts` add constraint `carts_product_id_foreign` foreign key (`product_id`) references `products` (`id`) on delete cascade)

我的迁移代码是这样的:carts迁移文件

public function up()
{
Schema::create('carts', function (Blueprint $table) {
$table->bigIncrements('id');
$table->integer('product_id')->unsigned();
$table->integer('customer_id')->unsigned();
$table->foreign('product_id')->references('id')->on('products')->onDelete('cascade');
$table->foreign('customer_id')->references('id')->on('customers')->onDelete('cascade');
$table->string('quantity');
});
}

产品迁移文件

public function up()
{
Schema::create('products', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name');
$table->string('unit');
$table->decimal('price', 6, 3);
$table->string('img_url');
$table->string('description');
$table->integer('sold');
$table->integer('in_stock');

});
}

客户迁移文件

public function up()
{
Schema::create('customers', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('first_name');
$table->string('last_name');
$table->string('phone_number');
$table->string('address');
$table->string('zip')->nullable();
$table->string('email')->unique();
$table->string('user_name')->unique();
$table->string('password');
});
}

任何关于我做错了什么的想法,我现在就想得到,因为我有很多表格需要创建,例如购物车、产品、客户。理想情况下,我想创建carts表,用外键保存这些数据,即product_id和cart_id

尝试使用此结构。

$table->foreignIdFor(Product::class);
$table->foreign('product_id')->references('id')->on('products');
$table->foreignIdFor(Customer::class);
$table->foreign('customer_id')->references('id')->on('customers');

此外,请确保您的产品和客户迁移在Carter迁移之前运行,并且您的模型已导入到迁移中。

您可以这样使用。

$table->unsignedBigInteger('product_id')->nullable();
$table->foreign('product_id')->references('id')->on('products');
$table->unsignedBigInteger('customer_id')->nullable();
$table->foreign('customer_id')->references('id')->on('customers');

最新更新