【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)

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM