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();
});