Laravel 当字段类型为字符串SQLSTATE[HY000]时,我有一个迁移问题:一般错误:1215
我把桌子连接起来,这样Laravel 当字段类型为字符串SQLSTATE[HY000]时,我有一个迁移问题:一般错误:1215,laravel,migration,schema,Laravel,Migration,Schema,我把桌子连接起来,这样 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` (
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
怎么系?整型字段没有问题。只能有一个外键引用唯一的字段。修改城市表,使ref字段唯一,如下所示:
//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');
});
只能有引用唯一字段的外键。修改城市表,使ref字段唯一,如下所示:
//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');
});
列必须被索引
为了创建外键约束,必须对链接到的表上的列编制索引。我建议您在cities表中将ref
字段设置为唯一字段,从而为其提供索引,并确保您只有一个项目可链接
// cities
$table->string('ref')->unique();
列必须被索引
为了创建外键约束,必须对链接到的表上的列编制索引。我建议您在cities表中将ref
字段设置为唯一字段,从而为其提供索引,并确保您只有一个项目可链接
// cities
$table->string('ref')->unique();
确保默认情况下表引擎设置为InnoDB,或者使用$table->engine='InnoDB'显式设置它 这里还有5.8版的文档,希望对您有所帮助
确保默认情况下将table engine设置为InnoDB,或者使用$table->engine='InnoDB'显式设置它 这里还有5.8版的文档,希望对您有所帮助 谢谢!你帮了我!“+1”谢谢!你帮了我!"+1"