CakePHP: associating two models using different da

2019-05-17 19:15发布

问题:

I have two models, Plant and Emp, that have a Has And Belongs To Many relationship. I've configured them to be associated and the query to get the data for each is correct, but the problem is Plant and Emp are on different databases. Emp is on Database 1, Plant is on Database 2. Because of this they don't query the join table properly; the join table is only on Database 1.

When the Plant model tries to access the join table it's querying Database 2, which does not have this data.

This is the association Emp has for Plant.

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

Update:I tried to set a "finderQuery" attribute to let me query the join table, but I don't know how to give a raw SQL query like that and allow it to dynamically use the id for the instance of the Model instead of a predefined value.

I can set something like

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

Which will give me the correct data for one employee, but I don't know how to make this finderQuery a dynamic query. There has to be a way for this to work.

回答1:

Try

var $useDbConfig = 'alternate';

in your Model Class.



回答2:

I needed to use a custom finderQuery and use the special {$__cakeID__$} identifier in place of the model ID being matched. This is a fixed version of the sample above, set as the finder query in the relationship entry for the $hasAndBelongsToMany array.

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

This works but if anyone knows how to fix this situation without a custom finder query (what I was trying to avoid by using associations) please post an answer and I will mark that correct instead.