更改codeigniter迁移的数据库连接

时间:2012-08-20 05:11:32

标签: php codeigniter

我想更改codeigniter迁移的数据库连接。

我的默认数据库是DB1,但我想更改与DB2的连接。

我该怎么做?默认编码如下。

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

2 个答案:

答案 0 :(得分:3)

dbforge库使用与CI的其他数据库部件相同的连接。由于只有一个连接,您必须更改该连接的数据库。如果您使用的是MYSQL,则可以使用两个use database calls

包围代码
// switch to the second db
$this->db->query('use DB2');

// put DB2 stuff here

// switch back    
$this->db->query('use DB'); 

答案 1 :(得分:0)

您可以使用

$this->load->database();

用于更改DB-Connection。在config / database.php中,您可以定义多个DB-Connections。例如,要更改为system-DB,请使用以下命令:

$this->load->database('system');

我将它用于迁移并将命令放在我的Migrate-Controller的构造函数中。

class Migrate extends CI_Controller
{
    function __construct()
    {
        parent::__construct();
        $this->load->database('system'); //Use the system-Connection for DB-Manipulation
        $this->load->library('migration');
    }

    /**
     * Migrate to latest or current version
     * @return void
     */
    public function index()
    {
        ...