【问题标题】:CakePHP: associating two models using different databases?CakePHP:使用不同的数据库关联两个模型?
【发布时间】:2011-09-02 17:07:46
【问题描述】:

我有两个模型,Plant 和 Emp,它们具有 Has And Belongs 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'             => '',
)
);

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

我可以设置类似的东西

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

这将为我提供 one 员工的正确数据,但我不知道如何使这个 finderQuery 成为动态查询。必须有办法让这个工作。

【问题讨论】:

    标签: php model-view-controller cakephp


    【解决方案1】:

    试试

    var $useDbConfig = 'alternate';
    

    在您的模型类中。

    【讨论】:

    • 两种型号都有正确的数据库配置,不过我已经更新了我的问题
    【解决方案2】:

    我需要使用自定义 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])' 
    

    这可行,但如果有人知道如何解决这种情况没有自定义查找器查询(我试图通过使用关联来避免)请发布答案,我会将其标记为正确。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-15
      • 2015-01-28
      • 1970-01-01
      相关资源
      最近更新 更多