简体   繁体   English

laravel迁移中如何修改外键引用表名

[英]How to change foreign key reference table name in laravel migration

I have this line in a migration table我在迁移表中有这一行

Schema::create('xyzTableName', function (Blueprint $table) {
    $table->id();
    $table->unsignedBigInteger('userId');
    $table->foreign('userId')->references('id')->on('userId');
    $table->timestamps();
});

where I did write on('userId') by mistake what I want is on('users')在 ('userId')上写错了我想要的是on('users')

now I did this, (in a new migration, as I can't run migrate:fresh )现在我这样做了,(在新的迁移中,因为我不能运行migrate:fresh

 Schema::create('xyzTableName', function (Blueprint $table) {
            $table->foreign('userId')->references('id')->on('users')->change();
        });

but I don't why it is not working, please help me但我不知道为什么它不起作用,请帮助我

You can drop the old key and build a new one您可以删除旧密钥并构建一个新密钥

Schema::table('xyzTableName', function (Blueprint $table) {
    $table->dropForeign('xyzTableName_users_userId_foreign');
    $table->foreign('userId')->references('id')->on('users');
});

Laravel will always try to create the keys using its patterns. Laravel 将始终尝试使用其模式创建键。 Since you didn't follow the name and field pattern recommended by laravel I can't be sure that string 'xyzTableName_users_userId_foreign' will be the correct one.由于您没有遵循 laravel 推荐的名称和字段模式,我无法确定字符串“xyzTableName_users_userId_foreign”是否正确。

Check in your database the foreign key name.将外键名称签入您的数据库。 This is the command I'd use If MySQL这是我使用的命令 If MySQL

SELECT
    TABLE_NAME,
    COLUMN_NAME,
    CONSTRAINT_NAME,
    REFERENCED_TABLE_NAME,
    REFERENCED_COLUMN_NAME
FROM
    INFORMATION_SCHEMA.KEY_COLUMN_USAGE
WHERE
    REFERENCED_TABLE_SCHEMA = 'db_name'
    AND REFERENCED_TABLE_NAME = 'table_name'
    AND REFERENCED_COLUMN_NAME = 'column_name';

Reference 参考

In the Model you can give table with protect.在 Model 中,您可以给表提供保护。

namespace App\Models;

class Category extends Model
{

protected $table = 'new_table_name';


}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM