[英]Is it possible to create a foreign key relationship between two tables on String/varchar type columns in Laravel?
I have a categories table which has an id and a slug(varchar type) column.I want to create a subcategories table which will have a column category_slug(varchar type) that will reference the slug column in the Category table. 我有一个类别表,其中有一个ID和一个Slug(varchar type)列。我想创建一个子类别表,该子类别表将具有一个category_slug(varchar type)列,该列将引用Category表中的slug列。
I am getting errors during php artisan migrate. 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();
});
The errors in the terminal are. 终端中的错误是。
[Illuminate\\Database\\QueryException] SQLSTATE[HY000]: General error: 1005 Can't create table
laravel_eshopper
. [Illuminate \\ Database \\ QueryException] SQLSTATE [HY000]:常规错误:1005无法创建表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
))#sql-ee8_272
(错误号:150“外键约束#sql-ee8_272
不正确”)(SQL:更改表tabpanes
添加约束tabpanes_category_slug_foreign
外键(category_slug
)引用categories
(slug
))[PDOException] SQLSTATE[HY000]: General error: 1005 Can't create table
laravel_eshopper
. [PDOException] SQLSTATE [HY000]:常规错误:1005无法创建表laravel_eshopper
。#sql-ee8_272
(errno: 150 "Foreign key constraint is incorrectly formed")#sql-ee8_272
(错误号:150“外键约束#sql-ee8_272
不正确”)
Yes Surely You can do that See the Example Below: 是的,当然可以,请参见下面的示例:
Suppose you have your category table as below: 假设您的类别表如下:
Schema::create('categories', function (Blueprint $table) {
$table->increments('id');
$table->string('slug')->unique();
$table->timestamps();
});
Now You can create subcategories with foreign key as below: 现在,您可以使用外键创建子类别,如下所示:
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();
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.