你能帮助我吗?
我使用MySQL。
我做的
php artisan migrate
但是错误
illumed\Database\QueryException:SQLSTATE[HY000]:一般错误:
1005无法创建表
learn
products
(errno:150“外键约束格式不正确)(SQL:alter table
products
add约束外键(
products_category_id_foreign
)参考文献)
category_id
迁移: Schema::create('categories', function (Blueprint $table) {
$table->increments('id');
$table->string('name', 50)->unique();
$table->timestamps();
$table->softDeletes();
});
categories
迁移: Schema::create('products', function (Blueprint $table) {
$table->increments('id');
$table->string('name', 150)->unique();
$table->unsignedBigInteger('category_id');
$table->string('image', 255);
$table->boolean('sale')->default(false);
$table->text('description');
$table->timestamps();
$table->softDeletes();
$table->foreign('category_id')->references('id')->on('categories');
});
最佳答案
替换:$table->unsignedBigInteger('category_id');
使用:$table->integer('category_id')->unsigned();
或者
替换:$table->increments('id');
使用:$table->bigIncrements('id');
在两个表中(但至少在categories表中)。
为什么?:
来自MySQL文档:https://dev.mysql.com/doc/refman/5.6/en/create-table-foreign-keys.html
外键和引用键中的相应列必须具有相似的数据类型。整数类型的大小和符号必须相同。字符串类型的长度不必相同。对于非二进制(字符)字符串列,字符集和排序规则必须相同。
从拉维尔文件:https://laravel.com/docs/5.8/migrations#columns
$table->increments():自动递增无符号整数(主键)等效列。
$table->unsignedbiginger():无符号BIGINT等效列。
所以在你的情况下:$table->unsignedBigInteger('category_id');
=>无符号BIGINT$table->increments('id');
=>无符号整数。
它们不匹配。
关于php - 外键约束格式错误。你能帮助我吗?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/57421072/