我想在laravel中重命名外键。
这就是我创建的:
Schema::create('holidays', function (Blueprint $table) {
$table->increments('id');
$table->timestamps();
$table->integer('account_id')->unsigned();
$table->date('holiday_date');
});
if (Schema::hasTable('accounts')) {
Schema::table(
'holidays',
function (Blueprint $table) {
$table->foreign('account_id')->references('id')->on('accounts')->onDelete('cascade');
}
);
}
现在,我想将account_id更改为gingagement_id。如何做?
应该是这样的:
注意:在重命名外国之前,您必须删除旧外国并分配新的
class RenameColumn extends Migration
{
public function up()
{
Schema::table('holidays', function(Blueprint $table) {
$table->dropForeign('holidays_account_id_foreign');
$table->renameColumn('account_id', 'engagement_id');
$table->foreign('engagement_id')->references('id')->on('accounts')->onDelete('cascade');
});
}
public function down()
{
Schema::table('holidays', function(Blueprint $table) {
$table->dropForeign('holidays_engagement_id_foreign');
$table->renameColumn('account_id', 'engagement_id');
$table->foreign('account_id')->references('id')->on('accounts')->onDelete('cascade');
});
}
}
@rborum解释的内容需要安装学说/DBAL包。否则,您可以直接执行SQL查询以重命名您的密钥或进行其他任何更改。
我能够执行此操作而不会丢下列。
非常简单:
public $oldIndex = 'old_constraint_name_foreign';
public $newIndex = 'new_constraint_name_foreign';
public $oldColumn = 'old_column_name';
public $newColumn = 'new_column_name';
Schema::table('my_table', function (Blueprint $table) {
$table->renameIndex($this->oldIndex, $this->newIndex);
$table->renameColumn($this->oldColumn, $this->newColumn);
});
您需要使用以下方式进行新的迁移: php artisan make:migration rename_column
内部:
class RenameColumn extends Migration
{
public function up()
{
Schema::table('accounts', function(Blueprint $table) {
$table->renameColumn('account_id ', 'engagement_id');
});
}
public function down()
{
Schema::table('accounts', function(Blueprint $table) {
$table->renameColumn('account_id ', 'engagement_id');
});
}
}
然后执行您的迁移: php artisan migrate
如果您尚未拥有它,则需要学说。您可以通过
的作曲家获得这个 composer require doctrine/dbal