你能帮帮我吗?
我用的是MySQL。
我做
php artisan migrate
但是错误
Illuminate\Database\QueryException : SQLSTATE[HY000]: General error: 1005 Can't create table
learn
.products
(errno: 150 "Foreign key constraint is incorrectly formed") (SQL: alter tableproducts
add constraintproducts_category_id_foreign
foreign key (category_id
) referencescategories
(id
))
类别
迁移:
Schema::create('categories', function (Blueprint $table) {
$table->increments('id');
$table->string('name', 50)->unique();
$table->timestamps();
$table->softDeletes();
});
产品
迁移:
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');
在两个表中(但至少在您的类别表中)。
为什么?
来自 MySQL 文档:https://dev.mysql.com/doc/refman/5.6/en/create-table-foreign-keys.html
Corresponding columns in the foreign key and the referenced key must have similar data types. The size and sign of integer types must be the same. The length of string types need not be the same. For nonbinary (character) string columns, the character set and collation must be the same.
来自 Laravel 文档:https://laravel.com/docs/5.8/migrations#columns
$table->increments(): Auto-incrementing UNSIGNED INTEGER (primary key) equivalent column.
$table->unsignedBigInteger(): UNSIGNED BIGINT equivalent column.
所以在你的情况下:
$table->unsignedBigInteger('category_id');
=> UNSIGNED BIGINT
$table->increments('id');
=> 无符号整数。
它们不匹配。
关于php - 外键约束的格式不正确。你能帮助我吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57421072/