在CakePHP新的ORM中,您可以使用QueryBuilder构建(理论上)任何查询。
我想根据另一个值选择两列中的一列的值。在常规查询中,可以按如下方式进行:
SELECT IF(from_id = 1, to_id, from_id) AS other_id FROM messages;
我正在尝试使用QueryBuilder和QueryExpression::addCase()
归档同一个查询$messagesQuery = $this->Messages->find('all');
$messagesQuery->select([
'other_id' => $messagesQuery->newExpr()->addCase(
$messagesQuery->newExpr()->add(['from_id' => $this->authUser->id]),
['to_id', 'from_id'],
['integer', 'integer']
)
]);
这不起作用,因为传递的值不是整数,而是包含整数的表列。
通过反复试验(再次使用方法add()
),我得到了以下内容:
$messagesQuery = $this->Messages->find('all');
$messagesQuery->select([
'other_id' => $messagesQuery->newExpr()->addCase(
$messagesQuery->newExpr()->add(['from_id' => $this->authUser->id]),
[
$messagesQuery->newExpr()->add(['to_id']),
$messagesQuery->newExpr()->add(['from_id'])
],
['integer', 'integer']
)
]);
这导致以下查询:
SELECT (CASE WHEN from_id = 1 THEN to_id END) AS `other_id` FROM messages Messages
现在,虽然CakePHP book states:
,ELSE
部分仍然缺失
只要条件条件少于值,addCase就会自动生成if .. then .. else语句。
examples in the CakePHP book在这种情况下不是很有用,因为它们只使用静态整数或字符串作为值,例如:
#SELECT SUM(CASE published = 'Y' THEN 1 ELSE 0) AS number_published, SUM(CASE published = 'N' THEN 1 ELSE 0) AS number_unpublished FROM articles GROUP BY published
$query = $articles->find();
$publishedCase = $query->newExpr()->addCase($query->newExpr()->add(['published' => 'Y']), 1, 'integer');
$notPublishedCase = $query->newExpr()->addCase($query->newExpr()->add(['published' => 'N']), 1, 'integer');
$query->select([
'number_published' => $query->func()->sum($publishedCase),
'number_unpublished' => $query->func()->sum($unpublishedCase)
])
->group('published');
addCase
将两个表列用作值而不仅仅是静态值?答案 0 :(得分:1)
事实证明,在我之前的编辑中,我只是一个合乎逻辑的步骤。
作为CakePHP book correctly states:
只要条件条件少于值,addCase就会自动生成if .. then .. else语句。
为了使其工作,条件和值都必须是数组,即使只有一个条件。 (这篇CakePHP书没有说明。)
此代码:
$messagesQuery = $this->Messages->find('all');
$messagesQuery->select([
'other_id' => $messagesQuery->newExpr()->addCase(
[
$messagesQuery->newExpr()->add(['from_id' => $this->authUser->id])
],
[
$messagesQuery->newExpr()->add(['to_id']),
$messagesQuery->newExpr()->add(['from_id'])
],
['integer', 'integer']
)
]);
导致此查询:
SELECT (CASE WHEN from_id = 1 THEN to_id ELSE from_id END) AS `other_id` FROM messages Messages
尤里卡