1

我有一张桌子records和另一张桌子categories

我想获取此类别中的所有记录

$all_categories = '5,6,7,8';

所以我正在使用这段代码:

$query = $this->Records->find('all',[
    'contain' => ['Categories']
]);

if(!empty($search)){
    $query->where(['Records.title LIKE' => '%'.$search.'%']);
}

if(!empty($wilaya)){
    $query->where(['Records.adresse LIKE' => '%'.$wilaya.'%']);
}

if(!empty($cat)){
    $query->where(['Records.category_id =' => $cat]);
} else {
    $categories_array = explode(',',$all_categories);
    foreach($categories_array as $category) {
        $query->where(['Records.category_id =' => $category]);  
    }
}

当我使用它时,默认情况下我会得到AND-conditions 。

我怎样才能得到OR-conditions 呢?

4

2 回答 2

2

使用IN

$all_categories = '5,6,7,8';
$categories_array = explode(',',$all_categories);
$query->where(['Records.category_id IN' => $categories_array]);
于 2016-01-18T12:16:50.377 回答
1

这应该有效:

$all_categories = '5,6,7,8';
$array=explode(',',$all_categories);
$query->where(['Records.category_id' => $array], ['Records.category_id' => 'integer[]']);

注意:编辑答案以添加有关列数据类型的信息。在 CakePHP 3.x 中没有这个就无法工作。

这等于:

$all_categories = '5,6,7,8';
$array=explode(',',$all_categories);
$query->where(['Records.category_id IN' => $array]);

请参阅自动创建 IN 子句

于 2016-01-18T12:13:26.517 回答