简体   繁体   中英

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')

now I did this, (in a new migration, as I can't run 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. 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.

Check in your database the foreign key name. This is the command I'd use 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.

namespace App\Models;

class Category extends Model
{

protected $table = 'new_table_name';


}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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