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



我阅读了CodeIgniter关于迁移类的文档。我能够执行迁移,但我如何在迁移中使用down()函数?

下面是文档

中的示例
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');
    }

在我的页面中,我像这样设置迁移:

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);
    }
}

如何调用down()方法?

br

Migrations视为Git中的版本。

通过调用比当前更早的迁移来调用down()方法。

ts;博士

假设您的目录application/migrations/下当前时间有3个迁移文件。

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

因此,按照现在的情况,您的应用程序已经通过了上面列出的3次迁移,并且您的config/migration.php中的当前迁移状态设置为

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

您的表名为migrations, version设置为3

现在,当您通过迁移控制器运行$this->migration->current();时,它将不做任何事情,因为您已经处于当前迁移状态。


现在,不知怎么的,您创建博客的想法失败了,您希望您的应用程序返回到迁移状态002

你可以通过在控制器

中调用$this->migration->version(2);来调用它

在控制器的config.php$this->migration->current();中设置$config['migration_version'] = 2;

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

方法调用文件003_add_blog.php

最新更新