如何在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个回答

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.

dongtuanzi1080
dongtuanzi1080 非常好的解释非常感谢,但如果我更新现有表的结构,因为我被困在alter table。 谢谢
一年多之前 回复
drkbpwk609294
drkbpwk609294 很棒的解释。
接近 2 年之前 回复
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐