【问题标题】:change database connection of codeigniter migration更改 codeigniter 迁移的数据库连接
【发布时间】:2012-08-15 11:31:20
【问题描述】:

我想更改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');
}

【问题讨论】:

  • 您使用的是什么版本的 CI?

标签: php codeigniter


【解决方案1】:

你可以使用

$this->load->database();

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

$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()
    {
        ...    

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 2016-11-28
      • 2018-07-04
      • 2017-05-26
      • 1970-01-01
      • 2014-05-05
      • 1970-01-01
      • 2015-04-02
      • 1970-01-01
      • 2013-08-01
      相关资源
      最近更新 更多