CakePHP 3属于多个具有默认值的列

时间:2017-05-24 16:10:02

标签: php mysql cakephp cakephp-3.0

我有两张包含客户数据的表格。我需要在两列(primaryKey和customer_id)上进行连接。这里描述了问题和解决方案: How can I join two tables on multiple columns in CakePHP 3?

还有一些表包含客户和“全局”数据。全局数据适用于所有客户,并且可以通过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关系可以(如果是这样,怎么做)?

  

更新:它似乎还不起作用

$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'
        ]
    ]
]);

结果

...
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)
) 
...
  

第二次更新:

对不起我的仓促询问,我找到了解决方案:

$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)
) 

解决方案......

1 个答案:

答案 0 :(得分: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

  

更新:

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');

另见