首页 > 解决方案 > 使用 codeigniter 的迁移类创建数据库

问题描述

我想将 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

在我可以使用迁移类之前,似乎数据库必须已经存在。我是否正确并且需要在我首先创建数据库的迁移类周围编写一个包装器?

标签: phpdatabasecodeignitermigration

解决方案


您怀疑需要一种解决方法才能在迁移过程中创建数据库,这似乎是正确的。我不知道它是否可以被称为错误或缺少的功能,但它不会像写的那样做。

最大的问题是_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());
        }
    }
}

请知道我没有测试过这段代码。可能存在语法、逻辑或其他错误。如果不出意外,希望它能为您提供一个良好的起点


推荐阅读