MySQL/Laravel外键约束格式错误 [英] MySQL/Laravel Foreign key constraint is incorrectly formed
问题描述
我正在尝试运行php artisan migration以在laravel中创建我的mysql表.
I am trying to run php artisan migrate to create my mysql tables usin laravel.
我收到此错误: 外键约束格式不正确
I got this error: Foreign key constraint is incorrectly formed
用户表:
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('street');
$table->string('city');
$table->string('phone');
$table->string('email')->unique();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
password_resets表:
password_resets table:
Schema::create('password_resets', function (Blueprint $table) {
$table->string('email')->index();
$table->string('token');
$table->timestamp('created_at')->nullable();
});
产品表:
Schema::create('products', function (Blueprint $table) {
$table->increments('id');
$table->string('product_type');
$table->integer('quantity');
$table->timestamps();
});
发货表:
Schema::create('shipments', function (Blueprint $table) {
$table->increments('id');
$table->integer('order_number')->unsigned();
$table->integer('product_id')->unsigned();
$table->foreign('order_number')->references('id')->on('orders');
$table->foreign('product_id')->references('id')->on('products');
$table->dateTime('chargecardtime');
$table->dateTime('packingtime');
$table->date('shiporderdate');
$table->timestamps();
});
订单表:
Schema::create('orders', function (Blueprint $table) {
$table->increments('id');
$table->integer('customer_id')->unsigned();
$table->integer('product_id')->unsigned();
$table->foreign('customer_id')->references('id')->on('users');
$table->foreign('product_id')->references('id')->on('products');
$table->string('name');
$table->string('to_street');
$table->string('to_city');
$table->date('ship_date');
$table->string('phone');
$table->timestamps();
});
异常跟踪:
1 PDOException::(" SQLSTATE [HY000]:常规错误:1005无法创建表ec
.#sql-3664_86
(错误号:150外键约束格式不正确"))
1 PDOException::("SQLSTATE[HY000]: General error: 1005 Can't create table ec
.#sql-3664_86
(errno: 150 "Foreign key constraint is incorrectly formed")")
我猜想orders表有问题,因为出现错误后我看不到数据库中的那个表.其他人被创建了.
i guess there is a problem with orders table since after error i cant see that table in database.others are created.
推荐答案
由于引用的是id
,因此需要将外键列设置为unsigned
.由于ID默认情况下是无符号的(非负).
Since you're referencing an id
you need to make the foreign key column unsigned
. As ids are by default unsigned (non-negative).
对所有外键都这样做:
$table->integer('product_id')->unsigned();
这篇关于MySQL/Laravel外键约束格式错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!