query builder: IN clause with composite columns

倖福魔咒の 提交于 2019-12-24 06:13:14

问题


I need to create a IN conditions on multiple columns, like this

...
WHERE 
(order_date, order_number) IN (
    ('2016-03-11', 3455453), 
    ('2016-03-18', 83545454), 
    ('2016-06-17', 5354544)
)

starting from an array like this:

$orders = [
    ['2016-03-11', 3455453], 
    ['2016-03-18', 83545454], 
    ['2016-06-17', 5354544]
];

using cake3 query builder. I tried with

->where(['(order_date, order_number) IN' => $orders]);

but I get an error:

Cannot convert value to string

I know it's not hard to manually create the query manipulating the array, but I'd like to know if there is a cake way to do it.


回答1:


AFAICT this is not possible (yet) using the array syntax or regular comparison expressions, the code responsible for transforming only handles single fields and flat arrays, see

Source > \Cake\Database\Expression\Comparison::_stringExpression()

However, this is very well possible using a tuple comparison expression, which supports handling sets of tuples out of the box. Internally it is used by associations for handling composite keys.

use Cake\Database\Expression\TupleComparison;

// ...

$fields = ['order_date', 'order_number'];
$types = ['date', 'integer'];

$query->where(
    new TupleComparison($fields, $orders, $types, 'IN')
);

Source > \Cake\Database\Expression\TupleComparison



来源:https://stackoverflow.com/questions/37919141/query-builder-in-clause-with-composite-columns

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!