我有一个类别表,其中有一个 id 和一个 slug(varchar 类型)列。我想创建一个子类别表,其中包含一个列category_slug(varchar 类型),该列将引用类别表中的 slug 列。
我在 php artisan 迁移期间遇到错误。
Schema::create('subcategories', function (Blueprint $table) {
$table->increments('id');
$table->string('category_slug')->unique();
$table->integer('product_id');
$table->foreign('category_slug')
->references('slug')->on('categories');
$table->timestamps();
});
终端中的错误是。
[Illuminate\Database\QueryException] SQLSTATE[HY000]: General error: 1005 Can't create table
laravel_eshopper
.#sql-ee8_272
(errno: 150 "Foreign key constraint is incorrectly formed") (SQL: alter tabletabpanes
add constrainttabpanes_category_slug_foreign
foreign key (category_slug
) referencescategories
(slug
))[PDOException] SQLSTATE[HY000]: General error: 1005 Can't create table
laravel_eshopper
.#sql-ee8_272
(errno: 150 "Foreign key constraint is incorrectly formed")
最佳答案
是的,您当然可以做到这一点,请参阅下面的示例:
假设您的类别表如下:
Schema::create('categories', function (Blueprint $table) {
$table->increments('id');
$table->string('slug')->unique();
$table->timestamps();
});
现在您可以使用外键创建子类别,如下所示:
Schema::create('subcategories', function (Blueprint $table) {
$table->increments('id');
$table->string('category_slug')->unique();
$table->foreign('category_slug')
->references('slug')->on('categories')->onUpdate('cascade')
->onDelete('cascade');
$table->timestamps();
});
关于mysql - 是否可以在 Laravel 中的 String/varchar 类型列上的两个表之间创建外键关系?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45055943/