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

标签 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 关系来做到这一点?

UPDATE: It does not seem to work yet

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

2nd UPDATE:

抱歉我的仓促询问,我已经找到了解决方案:

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

这就是解决方案...

最佳答案

连接条件也可以表示为条件数组:

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

另请参阅

关于php - CakePHP 3 属于多个具有默认值的列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44163554/

相关文章:

php - CakePHP 3 中同一模型的多个关联

php - CakePHP:在 View 和元素中嵌入 CTP 文件名和路径

php - 如何在单个查询中将两个不同的数组值插入到表中

php - 注册功能

php - 为什么要使用 CakePHP 的 HTML Helpers?

javascript - 用户当前时间

mysql - SQL根据列值插入行?

php - 用 Volley 发送参数并获得响应

PHP setcookie 添加百分号

c# - MySQL 日期时间格式与 C# 失败