【发布时间】:2018-05-23 13:24:04
【问题描述】:
我有一个订单表和一个sell_shipping_labels,它将orders.id 引用为外国。但是,当我运行 Laravel 迁移时,我得到了可怕的错误代码:
[照亮\数据库\查询异常]
SQLSTATE[HY000]: 一般错误: 1005 Can't create tablecheapbooks_test.#sql-b5b_b2a(errno: 150 "外键约束格式不正确") (SQL: alter tablesell_shipping_labelsadd constraintsell_shipping_labels_order_id_foreignforeign key (order_id) 引用orders(id))[Doctrine\DBAL\Driver\PDOException]
SQLSTATE[HY000]: 一般错误: 1005 无法创建表cheapbooks_test.#sql-b5b_b2a(errno: 150 "外键约束格式不正确")
这是我的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');
});
}
现在我颠倒了互联网试图找出问题所在。所有关于这个问题的帖子都提到必须在 BEFORE 上面创建外键的表之前创建订单表,但这对我来说不是问题,因为我的文件在正确的顺序。
【问题讨论】:
-
Laravel 7+ 允许你使用
$table->foreignId('order_id')->constrained();而不是$table->foreign('order_id')->references('id')->on('orders'); -
@afaolek 建议对我有用。虽然没有尝试过其他答案(无论如何都不需要)
标签: mysql laravel laravel-5 laravel-artisan artisan-migrate