【TP3.2】跨库操作和跨域操作

一、跨库操作:(同一服务器,不同的数据库)

假设UserModel对应的数据表在数据库user下面,而InfoModel对应的数据表在数据库info下面,那么我们只需要进行下面的设置即可。

class UserModel extends Model {
    protected $dbName = 'user';
}
class InfoModel extends Model {
    protected $dbName = 'info';
}

在进行查询的时候,系统能够自动添加当前模型所在的数据库名。

$User = D('User'); 
$User->select();
echo $User->getLastSql();
// 输出的SQL语句为 select * from user.think_user ,前缀不用管,在配置文件里面

模型的表前缀取的是项目配置文件定义的数据表前缀,如果跨库操作的时候表前缀不是统一的,那么我们可以在模型里面单独定义表前缀,例如:

protected $tablePrefix = 'other_';

 

如果你没有定义模型类,而是使用的M方法操作的话,也可以支持跨库操作,例如:

$User = M('user.User','other_'); 

 上面表示:user库,other_User表

 

二、跨域操作:(不同服务器,不同数据库)

用法很简单, 只需要调用Model类的db方法,用法:

 

Model->db("数据库编号","数据库配置");

 1)在Model类(XXModel.class.php)里面使用:

$this->db(1,"mysql://root:123456@localhost:3306/test")->query("查询SQL");
//或者
$this->db(1,"DB_CONFIG1")->query("查询SQL");
$this->db(2,"DB_CONFIG2")->query("查询SQL");
//或者指定表进行其他操作
$this->db(1)->table("top_user")->find();

 2)在控制器类(Controller.class.php)里面使用:

$obj = M('deal_item','xxf_','DB_CONFIG2');
$list = $obj->select('132');

 3)可以预先在公共配置文件,进行配置,如下:

//数据库配置1
'DB_CONFIG1' = array(
    'db_type'  => 'mysql',
    'db_user'  => 'root',
    'db_pwd'   => '1234',
    'db_host'  => 'localhost',
    'db_port'  => '3306',
    'db_name'  => 'thinkphp'
),
//数据库配置2
'DB_CONFIG2' => 'mysql://root:1234@localhost:3306/thinkphp';

以上三种,推荐2)+3)

 

posted @ 2017-09-11 17:00  PHP急先锋  阅读(2039)  评论(0编辑  收藏  举报