2017-05-24 44 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