2017-05-24 43 views
0

我有两个客户数据表。我需要在两列(primaryKey和customer_id)上进行连接。这里描述的问题和解决方案如下: How can I join two tables on multiple columns in CakePHP 3?CakePHP 3 belongsTo通过多列使用默认值

也有一些包含customer和“global”数据的表。全球数据适用于所有客户,并可通过customer_id“0”识别。

结果应该是这样的:

SELECT * FROM 
    table1 
INNER JOIN 
    table2 
ON (table1.table2_id = table2.id AND 
    (table1.customer_id=table2.customer_id OR table2.customer_id=0)) 
WHERE 1; 

是否有可能(如果有的话,如何)与CakePHP的关系,做到这一点?

更新:它似乎并没有在

... 
INNER JOIN calibrations Calibrations ON (
    Foods.calibration_id = Calibrations.id 
AND (
    Foods.tenant_id = 'Calibrations.tenant_id' 
    OR Calibrations.tenant_id = 0 
) 
    AND Calibrations.id = (Foods.calibration_id) 
) 
... 

月2日更新工作尚未

$this->belongsTo('Calibrations', [ 
    'foreignKey' => 'calibration_id', 
    'joinType' => 'INNER', 
    'conditions' => [ 
     'Foods.calibration_id = Calibrations.id', 
     'OR' => [ 
      'Foods.tenant_id' => 'Calibrations.tenant_id', 
      'Calibrations.tenant_id' => '0' 
     ] 
    ] 
]); 

结果:

对不起我的草率调查,我已经找到了解决办法:

$this->belongsTo('Calibrations', [ 
    'foreignKey' => 'calibration_id', 
    'joinType' => 'INNER', 
    'conditions' => [ 
     'OR' => [ 
      'Foods.tenant_id = Calibrations.tenant_id', 
      'Calibrations.tenant_id' => '0' 
     ] 
    ] 
]); 

结果

INNER JOIN calibrations Calibrations ON (
(
    Foods.tenant_id = Calibrations.tenant_id 
    OR Calibrations.tenant_id = 0 
) 
    AND Calibrations.id = (Foods.calibration_id) 
) 

那解...

+0

请用英文。 – aynber

+0

感谢翻译很好 – chriss

回答

0

加入条件也可以表示为条件的数组:

$query = $this->Table1->find() 
    ->hydrate(false) 
    ->join([ 
     't2' => [ 
      'table' => 'table2', 
      'type' => 'INNER', 
      'conditions' => [ 
       'Table1.table2_id = t2.id', 
       'OR' => [ 
        [ 
         'Table1.customer_id' => 't2.customer_id', 
         't2.customer_id' => '0' 
        ] 
       ] 
      ] 
     ] 
    ]); 

另请参见Adding Joins

UPDATE:

同样可以用contain()来完成:

// Table1 
    $this->belongsTo('Table2', [ 
     'className' => 'Table2', 
     'foreignKey' => 'table2_id', 
     'joinType' => 'INNER', 
     'conditions' => [ 
       'Table1.table2_id = Table2.id', 
       'OR' => [ 
        [ 
         'Table1.customer_id' => 'Table2.customer_id', 
         'Table2.customer_id' => '0' 
        ] 
       ] 
      ] 
    ]); 

    // Controller 
    $query = $this->Table1->find() 
     ->contain('Table2'); 

参见

+0

感谢您的快速回复。我认为这将是一种“解决方法”解决方案。如果它是自动/配置的,我宁愿拥有它,然后我可以将它外包给行为。背景应该是一个SaaS解决方案,我不希望开发人员担心。模型应该自己做... – chriss

+0

好吧,检查我的更新。 –

+0

这看起来像是正确的解决方案。我明天会测试它。非常感谢您的快速回复... – chriss