使用codeigniter的迁移类创建数据库

时间:2018-11-11 15:15:38

标签: php database codeigniter migration

我想将Codeigniter的迁移类集成到项目的构建过程中。我可以使用迁移类来创建数据库,还是仅用于更新数据库结构?

我的迁移类如下:

class Migration_base extends CI_Migration {
 public function up()
 {
   $this->dbforge->create_database('my_db');
 }
 public function down()
 {
   $this->dbforge->drop_database('my_db');
 }
}

当我运行此代码时:

class Migrate extends CI_Controller
{
    public function index()
    {
            $this->load->library('migration');

            if ($this->migration->current() === FALSE)
            {
                    show_error($this->migration->error_string());
            }
        }

}

我收到此消息:

Database error: A Database Error Occurred
        Unable to connect to your database server using the provided settings.
        Filename: path_to_codeigniter/codeigniter/framework/system/database/DB_driver.php
        Line Number: 436

似乎我必须先存在数据库,然后才能使用迁移类。我是正确的,是否需要在我首先创建数据库的迁移类周围编写包装器?

1 个答案:

答案 0 :(得分:1)

您怀疑需要一种变通办法才能在迁移过程中创建数据库,这似乎是正确的。我不知道它是否可以称为错误或缺少功能,但不会按书面要求执行。

最大的问题是,该类创建的_migration_table必须位于要迁移的数据库中。一个典型的“鸡还是蛋”问题。

文档中假定并没有解决的另一个可能的问题是,要迁移的数据库是应“加载”的数据库。

我认为您的Migrate控制器的以下版本将同时解决这两个问题。

class Migrate extends CI_Controller
{
    public function index()
    {
        if( ! isset($this->db))
        {
            throw new RuntimeException("Must have a database loaded to run a migration");
        }

        // Are we connected to 'my_db' ?
        if( ! $this->db->database !== 'my_db')
        {
            //find out if that db even exists
            $this->load->dbutil();
            if( ! $this->dbutil->database_exists('my_db'))
            {
                // try to create 'my_db'
                $this->load->dbforge();
                if( ! $this->dbforge->create_database('my_db'))
                {
                    throw new RuntimeException("Could not create the database 'my_db");
                }
            }

            // Connection data for 'my_db' must be available 
            // in /config/database.php for this to work.
            if(($db = $this->load->database('my_db', TRUE)) === TRUE)
            {
                $this->db = $db;  //replace the previously loaded database
            }
            else
            {
                throw new RuntimeException("Could not load 'my_db' database");
            }
        }

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

        if($this->migration->current() === FALSE)
        {
            show_error($this->migration->error_string());
        }
    }
}

请知道我尚未测试此代码。可能存在语法,逻辑或其他错误。如果没有其他希望,它可以为您提供一个良好的起点