【问题标题】:Codeigniter Migration to Alter a TableCodeigniter 迁移以更改表
【发布时间】:2015-04-02 05:28:31
【问题描述】:

我在 codeigniter 中创建了一个 Migration 来创建一个包含 4 列的 MySQL 表。现在我想更改其中一列的名称,而不会丢失该表中的数据。

首先,我已启用迁移并将版本设置为 1。 然后,我创建了一个file 001_create_users.php 并添加了以下代码。

class Migration_Create_users extends CI_Migration {

    public function up(){

        $this->dbforge->add_field(
            array(
                'id'        => array('type'=>'INT', 'constraint'=>11, 'unsigned'=>TRUE, 'auto_increment'=>TRUE),
                'email'     => array('type'=>'VARCHAR', 'constraint'=>100),
                'password'  => array('type'=>'VARCHAR', 'constraint'=>255),
                'created'      => array('type'=>"TIMESTAMP DEFAULT CURRENT_TIMESTAMP")
            )
        );

        $this->dbforge->add_key('id');
        $this->dbforge->create_table('users');

    }

    public function down(){

        $this->dbforge->drop_table('users');

    }
}

现在我想将列名“date”更改为“created_at”。那么我该怎么做呢?我的意思是最好的方法是什么? 还有谁能解释我如何进行回滚?因为我使用了以下控制器来运行迁移。

class Migration extends Admin_Controller{

    public function __construct(){
        parent::__construct();
    }

    public function index($version){

        $this->load->library('migration');

        if( !$this->migration->version($version)){
            show_error($this->migration->error_string());
        }
        echo "I'm in Migration";
    }

}

所以,如果我运行http://localhost/migration/index/1,它将运行 up() 函数。我应该怎么做才能通过浏览器执行回滚?我可以创建另一个方法并调用它吗?

我仍然不明白迁移的实际工作原理,谁能给我解释一下?

【问题讨论】:

    标签: php mysql codeigniter migration database-migration


    【解决方案1】:

    您可以尝试浏览 http://localhost/migration/index/0 以返回到版本 0。或者您可以创建单独的函数“回滚”以回滚到特定版本,并使索引函数仅使用 $this->migration->current() 向上迁移

    【讨论】:

    • 如果我去localhost/migration/index/0 是回滚吗?这会调用 001_Migrations 中的 down() 函数吗?或者你能解释一下如何写回滚吗?
    • 基本上,对于回滚,您需要使用您已经在使用的$this->migration->version()。您可以从数据库中的迁移表中检查当前版本。转到任何以前的版本都是回滚。因此,基本上当您调用$this->migration->version(<version_num>) 时,CI 会检查数据库并决定是回滚还是向上迁移。希望这能回答您的问题。
    • 是的,我明白了。谢谢。
    猜你喜欢
    • 2012-08-15
    • 2016-02-26
    • 2017-05-26
    • 1970-01-01
    • 1970-01-01
    • 2016-11-28
    • 2015-12-31
    • 2012-04-12
    • 1970-01-01
    相关资源
    最近更新 更多