我有一个已经创建外键约束的表:
$table->foreign('cms_id')->references('id')->on('inventories');
我需要更改此外键,以便它引用 remote_id
而不是 inventories
表中的 id
列。
我已经尝试这样做了:
public function up()
{
Schema::table('contents', function (Blueprint $table) {
$table->dropForeign('contents_cms_id_foreign');
$table->foreign('cms_id')->references('remote_id')->on('inventories');
});
}
但是,我得到:
[Illuminate\Database\QueryException]
SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL : alter tablecontents
add constraintcontents_cms_id_foreign
foreign k ey (cms_id
) referencesinventories
(remote_id
))[PDOException]
SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint
最佳答案
分两步添加新的外键,除了分离到Schema::table
:
public function up()
{
Schema::table('contents', function (Blueprint $table) {
$table->dropForeign('contents_cms_id_foreign');
$table->integer('cmd_id')->unsigned();
});
Schema::table('contents', function (Blueprint $table) {
$table->foreign('cms_id')->references('remote_id')->on('inventories');
});
}
关于php - Laravel 改变外键约束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44671525/