如何在这里使用OR条件

时间:2016-01-18 12:09:56

标签: php mysql cakephp cakephp-3.x

我有一张表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条件。

我如何获得OR - 条件呢?

2 个答案:

答案 0 :(得分:2)

使用IN

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

答案 1 :(得分: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]);

请参阅Automatically Creating IN Clauses