我有一个表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
条件?
使用 IN
:
$all_categories = '5,6,7,8';
$categories_array = explode(',',$all_categories);
$query->where(['Records.category_id IN' => $categories_array]);
这应该有效:
$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 子句。