CakePHP:使用不同的数据库关联两个模型


CakePHP: associating two models using different databases?

我有两个模型,Plant和Emp,它们具有Has和belong To Many关系。我已经将它们配置为关联的,并且查询每个数据是正确的,但问题是Plant和Emp在不同的数据库上。Emp在数据库1上,Plant在数据库2上。因此,它们不能正确地查询连接表;连接表只在数据库1上。

当Plant模型试图访问连接表时,它查询的是没有该数据的数据库2。

这是Emp对Plant的关联。

var $hasAndBelongsToMany = array(
    'Plant' =>
        array(
            'className'              => 'Plant',
            'joinTable'              => 'emp_plant',
            'foreignKey'             => 'employee_id',
            'associationForeignKey'  => 'LocationID',
            'unique'                 => true,
            'conditions'             => '',
)
);

Update:我试图设置一个"finderQuery"属性来让我查询连接表,但我不知道如何给出这样的原始SQL查询,并允许它动态地使用模型的实例的id,而不是预定义的值。

我可以设置成

SELECT * FROM [Plant] AS [Plant] JOIN [DB].[DBO].[empplant] AS 
[EmpPlant] ON ([EmpPlant].[employee_id] = **4** 
AND [EmpPlant].[ID] = [Plant].[LocationID]) 

这将给我正确的数据一个员工,但我不知道如何使这个finderQuery动态查询。一定有办法让它起作用

Try

var $useDbConfig = 'alternate';

我需要使用自定义的finderQuery,并使用特殊的{$__cakeID__$}标识符来代替匹配的模型ID。这是上面示例的固定版本,设置为$hasAndBelongsToMany数组关系条目中的查找器查询。

'finderQuery'=>'SELECT * FROM [Plant] AS [Plant] JOIN [DB].[DBO].[empplant] AS 
[EmpPlant] ON ([EmpPlant].[employee_id] = {$__cakeID__$} 
AND [EmpPlant].[ID] = [Plant].[LocationID])' 

这是有效的,但如果有人知道如何解决这种情况没有一个自定义查找器查询(我是试图避免使用关联)请张贴答案,我会标记正确的,而不是。