我正在尝试向正在开发的查询中添加Case语句。在其中一个连接上,我需要添加要连接的字段的条件。 1.如果field1不为null,请使用它 2.否则,如果不为null,则使用field2 3.否则使用fallbackField。
我有一个仅使用sql的有效查询。但是希望将其转换。 我也有一个多重联接设置(只需要一个条件)
有效的原始sql
SELECT *
FROM customers c
INNER JOIN member_customers mc
ON c.id = mc.customer_id
INNER JOIN enums e
ON CASE
WHEN e.source_id IS NOT NULL
AND mc.id = e.source_id THEN 1
WHEN e.org_id IS NOT NULL
AND c.org_id = e.org_id THEN 1
ELSE e.enum_name = 'Sold'
END = 1
INNER JOIN enum_values ev
ON e.id = ev.enum_id
AND mc.state = ev.enum_value
WHERE mc.user_id = 999
GROUP BY c.NAME
我到目前为止的蛋糕转换
$query = $this->Customers->MemberCustomers->find('all')
->contain(['Customers'])
->join([
'c' => [
'table' => 'customers',
'type' => 'LEFT',
'conditions' => 'c.id = MemberCustomers.customer_id'
],
'e' => [
'table' => 'enums',
'type' => 'LEFT',
'conditions' => '//where the conditions need to be'
],
'ev' => [
'table' => 'enum_values',
'type' => 'LEFT',
'conditions' => 'e.id = ev.enum_id AND MemberCustomers.state = ev.enum_value'
]
])
答案 0 :(得分:0)
我找到了解决这个问题的方法。
$caseConditions = $query->newExpr()->addCase([
$query->newExpr()->add(['e.source_id IS NULL AND MemberCustomers.id = e.source_id']),
$query->newExpr()->add(['e.source_id IS NULL AND MemberCredentials.id = e.source_id'])
...
])
比条件部分
'conditions' => $caseConditions
答案 1 :(得分:0)
'e' => [
'table' => 'enums',
'type' => 'LEFT',
'conditions' =>
'(CASE WHEN e.source_id IS NOT NULL
AND mc.id = e.source_id THEN 1
WHEN e.org_id IS NOT NULL
AND c.org_id = e.org_id THEN 1
ELSE e.enum_name = 'Sold'
END) = 1'
]