沃梦达 / 编程问答 / php问题 / 正文

如何使用迁移重命名 laravel 中的列?

How can I rename column in laravel using migration?(如何使用迁移重命名 laravel 中的列?)

本文介绍了如何使用迁移重命名 laravel 中的列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有如下所述的列:

public function up()
{
    Schema::create('stnk', function(Blueprint $table)
    {
        $table->increments('id');
        $table->string('no_reg', 50)->unique();
        $table->string('no_bpkb', 50)->unique();
        $table->string('nama_pemilik', 100);
        $table->string('alamat');
        $table->string('merk', 50);
        $table->string('tipe', 50);
        $table->string('jenis', 50);
        $table->smallInteger('tahun_pembuatan');
        $table->smallInteger('tahun_registrasi');
        $table->smallInteger('isi_silinder');
        $table->string('no_rangka', 50);
        $table->string('no_mesin', 50);
        $table->string('warna', 50);
        $table->string('bahan_bakar', 50);
        $table->string('warna_tnkb', 50);
        $table->string('kode_lokasi', 50);
        $table->date('berlaku_sampai');
        $table->timestamps();

        $table->index('created_at');
        $table->index('updated_at');
    });

}

我已经为 stnk 表制作了播种机

现在我想将 id 重命名为 id_stnk.
我在 "composer" 中添加了一个 "doctrine/dbal" 并进行了 composer update.

Now I want to rename id to id_stnk.
I've added a "doctrine / dbal" in the "composer" and do a composer update.

我做了迁移php artisan migration:make rename_column.
然后我为 rename_column 添加了新方法:

I've made migration php artisan migration:make rename_column.
Then I've added new method to rename_column:

Schema::table('stnk', function(Blueprint $table)
{
    $table->renameColumn('id', 'id_stnk');

});

然后我尝试运行命令 php artisan migrate 但出现如下错误:

And then I've tried to run command php artisan migrate but I got error as mentioned bellow:

[UlluminateDatabaseQueryException]
SQLSTATE[HY000]: General error: 1025 Error on rename of './my_database/#sql -447_33' to './my_database/stnk' (error: 150) (SQL: ALTER TABLE stnk CHANGE id id_stnk INT UNSIGENED AUTO_INCREMENT NOT NULL)

[PDOException]
SQLSTATE[HY000]: General error: 1025  Error on rename  of './my_database/#sql -447_33' to './my_database/stnk' (error: 150)

推荐答案

您需要创建另一个迁移文件 - 并将其放置在其中:

You need to create another migration file - and place it in there:

运行

Laravel 4:    php artisan migrate:make rename_stnk_column
Laravel 5:    php artisan make:migration rename_stnk_column

然后在新的迁移文件里面放置:

Then inside the new migration file place:

class RenameStnkColumn extends Migration
{

    public function up()
    {
        Schema::table('stnk', function(Blueprint $table) {
            $table->renameColumn('id', 'id_stnk');
        });
    }


    public function down()
    {
        Schema::table('stnk', function(Blueprint $table) {
            $table->renameColumn('id_stnk', 'id');
        });
    }

}

这篇关于如何使用迁移重命名 laravel 中的列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:如何使用迁移重命名 laravel 中的列?

基础教程推荐