简体   繁体   English

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

[英]CakePHP: associating two models using different databases?

I have two models, Plant and Emp, that have a Has And Belongs To Many relationship. 我有两个模型,Plant和Emp,它们具有Has And Belongs To Many关系。 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. 我已经将它们配置为关联,并且获取每个数据的查询是正确的,但问题是Plant和Emp在不同的数据库上。 Emp is on Database 1, Plant is on Database 2. Because of this they don't query the join table properly; Emp位于数据库1上,Plant位于数据库2上。因此,它们不会正确查询连接表; the join table is only on Database 1. 连接表仅在数据库1上。

When the Plant model tries to access the join table it's querying Database 2, which does not have this data. 当Plant模型尝试访问连接表时,它将查询没有此数据的数据库2。

This is the association Emp has for Plant. 这是Emp为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. 更新 :我试图设置一个“finderQuery”属性让我查询连接表,但我不知道如何给出这样的原始SQL查询,并允许它动态地使用模型实例的id而不是预定义的值。

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. 这将为我提供一个员工的正确数据,但我不知道如何使这个finderQuery成为动态查询。 There has to be a way for this to work. 必须有一种方法可以实现这一点。

Try 尝试

var $useDbConfig = 'alternate';

in your Model Class. 在您的模型类中。

I needed to use a custom finderQuery and use the special {$__cakeID__$} identifier in place of the model ID being matched. 我需要使用自定义finderQuery并使用特殊的{$__cakeID__$}标识符代替匹配的模型ID。 This is a fixed version of the sample above, set as the finder query in the relationship entry for the $hasAndBelongsToMany array. 这是上面示例的固定版本,在$hasAndBelongsToMany数组的关系条目中设置为finder查询。

'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. 这有效,但如果有人知道如何修复这种情况没有自定义查找器查询(我试图通过使用关联避免),请发布一个答案,我将标记为正确。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM