使 CakePHP 查询生成器将子查询括在括号中

问题描述 投票:0回答:1

如何将子查询括在额外的括号中?

$sub = new \Cake\Database\Query();
$sub
  ->select('b.value')
  ->from(['b' => 'other_table'])
  ->where(['b.key' => 'fancy_cars'])
;

$query = new \Cake\Database\Query();
$query
  ->select(['a.id', 'a.name'])
  ->from(['a' => 'car'])
  ->where(['a.id MEMBER OF' => $sub])
;

背景:我有一个表,其中一个单元格中有一个 JSON 值,它是一个 ID 列表。

-- single parentheses is syntax error.
SELECT a.id, a.name FROM car AS a
WHERE a.id MEMBER OF (SELECT b.value FROM other_table AS b WHERE b.key = 'fancy_cars');

-- but this works.
SELECT a.id, a.name FROM car AS a
WHERE a.id MEMBER OF ((SELECT b.value FROM other_table AS b WHERE b.key = 'fancy_cars'));

-- underlying JSON value for comprehension.
SELECT id, name FROM my_resource WHERE id MEMBER OF ('[4, 192, 29, …]');


如何强制添加另一层括号?我尝试过的事情:

#1: another subquery nesting layer?
// … build sub the same way.
$sub2 = new \Cake\Database\Query();
$sub2->select($sub);

// …
$query->where(['a.id MEMBER OF' => $sub2]);

// ---

#2: array brackets?
$query->where(['a.id MEMBER OF' => [$sub]]);

cakephp/数据库3.8.1

mysql cakephp query-builder
1个回答
0
投票

newExpr
可以做到。

$query->where(['a.id MEMBER OF' => $query->newExpr($sub)]);
© www.soinside.com 2019 - 2024. All rights reserved.