在CodeIgniter中使用多个数据库 [英] Using Multiple Databases Within CodeIgniter

查看:122
本文介绍了在CodeIgniter中使用多个数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

免责声明:我是网络开发新手

DISCLAIMER: I'm new to web development

SCENARIO:我正在构建一个使用ion_auth来管理所有用户/管理员信息MySQL数据库),每个用户都有自己的数据库(MySQL),用于核心应用程序的目的。我已经在CodeIgniter中的applicaton / config / database.php文件中自动加载了我用于ion_auth的数据库。我使用标准的MVC格式(每个数据库的个别模型)。

SCENARIO: I'm building a web application that uses ion_auth to manage all of the user/administrator information (uses MySQL database), and each user has their own database (MySQL as well) for core application purposes. I've autoloaded the database that I'm using for ion_auth in the applicaton/config/database.php file within CodeIgniter. I am using standard MVC format (individual models pertaining to each database).

问题:我需要知道如何在CodeIgniter中轻松有效地使用多个数据库。我需要链接两个数据库模式在一起,还是CodeIgniter为我做这个?有没有解决这个问题的任何资源(我在尝试找到一个麻烦?)

ISSUE: I'm needing to know how to use multiple databases at once within CodeIgniter easily and efficiently. Do I need to link the two database schemas together, or will CodeIgniter do that for me? Are there any resources out there that address this issue (I've had trouble trying to find one)?

非常感谢您的帮助!

推荐答案

在您的数据库配置文件中添加与您的数据库的数量一样多的配置组:

in your database config file add as many configuration groups as the numbers of your databases:

$db['a']['hostname'] = 'localhost';
$db['a']['username'] = 'user';
$db['a']['password'] = 'pw';
$db['a']['database'] = 'db1';
...

$db['b']['hostname'] = 'localhost';
$db['b']['username'] = 'user';
$db['b']['password'] = 'pw';
$db['b']['database'] = 'db2';
...

//set the default db
$active_group = 'a';

然后在您的模型上初始化一个类变量:

then on your model initialize a class variable:

private $db_b;

,并将其设置如下:

__construct()
{
   ...
   $this->db_b = $this->load->database('b', TRUE); 
}

现在您可以使用数据库 b 照常:

now you are able to use the database b as usual:

$this->db_b->query('YOUR QUERY');

,显然默认的如下:

$this->db->query('YOUR QUERY');

这篇关于在CodeIgniter中使用多个数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆