cakephp2从两个数据库连接两个表

时间:2014-01-06 06:01:24

标签: mysql cakephp-2.0

我开发了一个基于SAAS的站点,我必须从两个DB连接两个表,比如来自DB1的table1和来自DB2的table2。我必须使用cakephp中的join来获取table1和table 2中的匹配记录,但是它会抛出错误,如下所示:

  

错误:SQLSTATE [42000]:语法错误或访问冲突:1142对表'table_name'的用户'dbname'@'localhost'拒绝SELECT命令。

任何人都可以解释我如何使用cakephp做到这一点。

class table1 extends AppModel{ 
public $useDbConfig = 'DB1'; 
} 
Class table2 extends AppModel{ 
public $useDbConfig = 'DB2'; 


function desc(){
    $this->Store->useDbConfig = 'default';

    $rslted = $this->find('all',array(
        'conditions' => array('Jewel.id' =>1),
        'joins' => array(
            array(
                'alias' => 'Store',
                'table' => 'stores',
                'type' => 'INNER',
                'conditions' => 'Store.id = Jewel.store_id'
            )
        )
    ));

    return $rslted;
}
}   

虽然从控制器调用desc函数不工作抛出错误:

  

未找到基表或视图:1146表'site1.site1_stores'不存在

但是在模型上使用hasmany或belongssto会起作用,连接查询在控制器中不起作用

1 个答案:

答案 0 :(得分:1)

请按照以下步骤操作:

步骤1:为模型类创建两个名为Jewel.php和Store.php的模型

Content of Jewel.php 
class Jewel extends AppModel{

    public $useDbConfig = 'DB1';

}
Content of Store.php 
Class Store extends AppModel{

    public $useDbConfig = 'DB2';

}

步骤2:在Store模型中创建一个方法,如下所示

function getData(){
   $this->bindModel(array(
                'hasOne' => array(
                  'Jewel' => array(
                           'foreignKey' => false,
                           'conditions' => array('Store.id = Jewel.store_id')
                  )
                 )
          ));
   $returnData = $this->find('all',array('conditions' => array('Jewel.id' =>1)));
}

希望这会有所帮助!