Laravel migration添加foreign key时提示错误:key column ‘xxx’ dons’t exist的原因和解决办法
admin 阅读:108 2024-03-04
Laravel migration添加foreign key时报错,错误信息为:key column 'xxx' dons't exist。错误代码如下:
Schema::create('emperors', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name');
$table->foreign('dynasty_id')->references('id')->on('dynasties')->onDelete('cascade');
$table->timestamps();
});
上面的代码在添加外键dynasty_id的时候报错,其实这是一个新手错误,没认真看文档,实际上在创建外键关系时,首先要创建该列,正确代码:
Schema::create('emperors', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name');
$table->unsignedInteger('dynasty_id')->nullable();
$table->foreign('dynasty_id')->references('id')->on('dynasties')->onDelete('cascade');
$table->timestamps();
});
声明
1、部分文章来源于网络,仅作为参考。 2、如果网站中图片和文字侵犯了您的版权,请联系1943759704@qq.com处理!