Laravel迁移(错误号:150“外键约束格式不正确") [英] Laravel migration (errno: 150 "Foreign key constraint is incorrectly formed")
问题描述
我有一个订单表,一个有sell_shipping_labels
,它引用orders.id
作为外来商品.但是,当我运行Laravel迁移时,我得到了可怕的错误代码:
I have an orders table and a have a sell_shipping_labels
which references orders.id
as a foreign. However when I run the Laravel migration I get the dreaded error code:
[Illuminate \ Database \ QueryException]
SQLSTATE [HY000]:常规错误:1005无法创建表cheapbooks_test
.#sql-b5b_b2a
(错误号:150外键约束格式不正确")(SQL:更改表sell_shipping_labels
添加约束sell_shipping_labels_order_id_foreign
外键(order_id
)引用orders
(id
))
[Illuminate\Database\QueryException]
SQLSTATE[HY000]: General error: 1005 Can't create tablecheapbooks_test
.#sql-b5b_b2a
(errno: 150 "Foreign key constraint is incorrectly formed") (SQL: alter tablesell_shipping_labels
add constraintsell_shipping_labels_order_id_foreign
foreign key (order_id
) referencesorders
(id
))
[Doctrine \ DBAL \ Driver \ PDOException]
SQLSTATE [HY000]:常规错误:1005无法创建表cheapbooks_test
.#sql-b5b_b2a
(错误号:150外键约束格式不正确")
[Doctrine\DBAL\Driver\PDOException]
SQLSTATE[HY000]: General error: 1005 Can't create table cheapbooks_test
.#sql-b5b_b2a
(errno: 150 "Foreign key constraint is incorrectly formed")
这是我的orders
表架构:
Schema::create('orders', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id');
$table->integer('book_id');
$table->integer('status_id');
$table->double('payment_amount')->nullable();
$table->timestamp('received_at')->nullable();
$table->timestamp('paid_at')->nullable();
$table->timestamps();
$table->softDeletes();
});
这是我的sell_shipping_labels
模式:
Schema::create('sell_shipping_labels', function (Blueprint $table) {
$table->increments('id');
$table->unsignedInteger('order_id');
$table->string('shippo_object_id');
$table->string('label_url');
$table->string('tracking_url');
$table->string('tracking_number');
$table->timestamp('arrived_at');
$table->timestamps();
$table->softDeletes();
$table->foreign('order_id')->references('id')->on('orders');
});
}
现在我已经颠倒了互联网,试图找出问题所在.有关此问题的所有帖子均指的是必须在其上具有外键的表上创建之前订单表的事实,但这对我来说不是问题,因为我的文件位于正确的顺序.
Now I've flipped the internet upside down trying to figure out the problem. All of the post about this problem all refer to the fact that the orders table must be created BEFORE the table that has the foreign key on it but this isn't a problem for me because my files are in the correct order.
推荐答案
由于increments()
创建了无符号整数列,因此您也需要将外键列也定义为无符号整数:
Since increments()
creates an unsigned integer column, you need to define the foreign key column as unsigned integer too:
$table->unsignedInteger('order_id');
或者:
$table->integer('order_id')->unsigned();
https://laravel.com/docs/5.5/migrations#foreign-关键约束
这篇关于Laravel迁移(错误号:150“外键约束格式不正确")的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!