dpy83214
dpy83214
2015-05-26 05:42

如何在CodeIgniter的迁移中使用down()方法?

已采纳

I read the CodeIgniter's documentation about the migration class. I am able to perform the migration but how can I use the down() function in the migration?

Here's the sample from the documentation

defined('BASEPATH') OR exit('No direct script access allowed');

class Migration_Add_blog extends CI_Migration {

    public function up()
    {
        $this->dbforge->add_field(array(
            'blog_id' => array(
                'type' => 'INT',
                'constraint' => 5,
                'unsigned' => TRUE,
                'auto_increment' => TRUE
            ),
            'blog_title' => array(
                'type' => 'VARCHAR',
                'constraint' => '100',
            ),
            'blog_description' => array(
                'type' => 'TEXT',
                'null' => TRUE,
            ),
        ));

        $this->dbforge->create_table('blog');
    }

    public function down()
    {
        $this->dbforge->drop_table('blog');
    }

In my page I setup the migration like this:

class Migrate extends CI_Controller {

    public function __construct() {
        parent::__construct();
        $this->load->library('migration');
    }

    public function index() {

        $this->load->helper('template');

        if(!$this->migration->current()) {
            show_error($this->migration->error_string());
        } else {
            $data['message'] = 'migrate success';
        }

        renderPage('common/migrate', $data);

    }

}

How can I call the down() method?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

1条回答

  • douxun1934 douxun1934 6年前

    tl;dr

    Think of Migrations as versions in Git.

    Invoke down() method by invoking older migration than current.

    ts;dr

    Lets say you have 3 migration files as per current time under your directory application/migrations/.

    1. 001_add_clients.php
    2. 002_add_customers.php
    3. 003_add_blog.php

    So, as per now your application has passed through 3 migrations as listed above and your current status of migration in your config/migration.php is set to

    $config['migration_table'] = 'migrations';
    $config['migration_version'] = 3;
    

    Your table named migrations has version set to 3.

    Now, when you run $this->migration->current(); through your migration controller, it will do nothing because your are already in current state of migration.


    Now, somehow your idea of creating blog failed and you want your application to return in migration state 002.

    You invoke this by calling $this->migration->version(2); in your controller

    or

    setting $config['migration_version'] = 2; in your config.php and $this->migration->current(); in your controller.

    This is the scenario where

    public function down()
    {
        $this->dbforge->drop_table('blog');
    }
    

    method invokes of file 003_add_blog.php.

    点赞 评论 复制链接分享

相关推荐