php - Laravel 改变外键约束

标签 php mysql laravel foreign-keys

我有一个已经创建外键约束的表:

$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 table contents add constraint contents_cms_id_foreign foreign k ey (cms_id) references inventories (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/

相关文章:

php - 在插件中扩展 WooCommerce COD 支付网关

php - 如何在 php 中使用 javascript 变量?

PHP mysqli_query 报语法错误

php - Laravel 5 isDirty() 总是返回 false

mysql - Laravel 推送通知 token : use Eloquent or Query builder?

php - 使用 Php 查询 SQL 并为 GeoPolygon 输出 geojson

php - 在 laravel 的 mysql 查询中获取计数

mysql - 选择用户每周至少出现一次,持续数周

mysql - Lua mysql,需要一种方法来转义数据

php - 如何过滤 groupBy() 以仅显示 Laravel 中每个组中的最高值?