我正在尝试使用 CodeIgniter 和 DBForge 创建一个多租户应用程序。我将有一个带有"users"表的中央数据库,该表将存储用户名及其数据库的名称。
我遇到的问题是创建单个数据库及其表。下面是一段代码:
if ($this->dbforge->create_database( $db_name ))
{
echo 'Database created!';
// an array of fields
$fields = array(
'name' => array(
'type' => 'VARCHAR',
'constraint' => '100',
),
);
// set them up for the new table
$this->dbforge->add_field($fields);
// create the new table in the new db
$this->dbforge->create_table('items');
}
创建数据库 $db_name 没有任何问题,但是当我创建表"items"时,它是在我的中央数据库上创建的,这不是我想要的。
嗨,当您尝试创建表时,它正在默认连接的数据库中创建表,您必须将数据库
与用户创建的数据库重新连接,并将该连接的数据库对象传递给 $this->db 并再次重新输入,而不是在用户数据库中创建表 在这里如何在用户数据库中创建表
if ($this->dbforge->create_database($db_name)) {
echo 'Database created!';
// an array of fields
$config['hostname'] = "localhost";
$config['username'] = "root";
$config['password'] = "";
$config['database'] = $db_name;
$config['dbdriver'] = "mysql";
$config['dbprefix'] = "";
$config['pconnect'] = FALSE;
$config['db_debug'] = TRUE;
$config['cache_on'] = FALSE;
$config['cachedir'] = "";
$config['char_set'] = "utf8";
$config['dbcollat'] = "utf8_general_ci";
$this->db = $this->load->database($config, TRUE); //<- magic start from here
$this->load->dbforge();
$fields = array(
'name' => array(
'type' => 'VARCHAR',
'constraint' => '100',
),
);
// set them up for the new table
$this->dbforge->add_field($fields);
// create the new table in the new db
$this->dbforge->create_table('items');
}
为了使您的代码更干净,请在应用程序/配置中创建一个user_db.php文件,并将用户配置放在那里,每次在代码中$config['数据库'] 时