簡體   English   中英

使用codeigniter的遷移類創建數據庫

[英]Create database with codeigniter's migration class

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

看來數據庫必須已經存在,才能使用遷移類。 我是否正確,是否需要在首先創建數據庫的遷移類周圍編寫包裝器?

您懷疑確實需要解決方法才能在遷移過程中創建數據庫。 我不知道它是否可以稱為錯誤或缺少功能,但不會按書面要求執行。

最大的問題是,該類創建的_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());
        }
    }
}

請知道我尚未測試此代碼。 可能存在語法,邏輯或其他錯誤。 如果沒有其他希望,它可以為您提供一個良好的起點

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM