In Connection.php line 664:
SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL: alter table `point_deliveries` add constraint `point_d
eliveries_city_ref_foreign` foreign key (`city_ref`) references `cities` (`ref`))
In Connection.php line 458:
SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint
我链接了表格,所以...
//parent
Schema::create('cities', function(Blueprint $table)
{
$table->increments('id');
$table->string('title')->nullable();
$table->string('ref');
$table->integer('country_id')->index()->unsigned()->nullable();
$table->foreign('country_id')->references('id')->on('countries');
});
//child
Schema::create('point_deliveries', function (Blueprint $table)
{
$table->increments('id');
$table->string('title')->nullable();
$table->string('ref')->nullable();
$table->string('city_ref');
$table->foreign('city_ref')->references('ref')->on('cities');
});
如何系好它们?字段整数没有问题。
答案 0 :(得分:1)
您只能有一个引用唯一字段的外键。修改您的城市表,使ref字段唯一,如下所示:
// cities
$table->string('ref')->unique();
答案 1 :(得分:1)
为了创建外键约束,必须对要链接到的表上的列建立索引。我建议您在城市表上使ref
字段唯一,从而为其指定索引,并确保仅链接一个项目。
//parent
Schema::create('cities', function(Blueprint $table)
{
$table->increments('id');
$table->string('title')->nullable();
$table->string('ref')->unique();;
$table->integer('country_id')->index()->unsigned()->nullable();
$table->foreign('country_id')->references('id')->on('countries');
});
//child
Schema::create('point_deliveries', function (Blueprint $table)
{
$table->increments('id');
$table->string('title')->nullable();
$table->string('ref')->nullable();
$table->string('city_ref');
$table->foreign('city_ref')->references('ref')->on('cities');
});
答案 2 :(得分:0)
确保默认情况下将表引擎设置为InnoDB,或者使用$ table-> engine ='InnoDB';显式设置它。
这也是5.8的文档,希望对您有所帮助。