CakePHP 3.6 Query Builder复杂OR条件问题

时间:2018-05-08 12:15:42

标签: cakephp-3.0 cakephp-3.5

我正在尝试使用具有复杂嵌套AND和OR条件的查询构建器来构建查询。这是我到目前为止所写的内容。

$cond_arr = array();
$cond_arr['VehicleBrandModels.status'] = 1;
$query = $this->VehicleBrandModels->find();
$query->hydrate(false);
$query->select($this->VehicleBrandModels);
$query->where($cond_arr);
$VBM_data = $query->toArray();

这将生成如下所示的查询

SELECT * FROM vehicle_brand_models WHERE status = 1;

我想用嵌套的AND&生成查询OR条件如下

SELECT * FROM vehicle_brand_models WHERE status = 1 AND ((overall_rating > 0 AND overall_rating < 2) OR (overall_rating >= 2 AND overall_rating < 4) OR (overall_rating >= 4 AND overall_rating <= 5));

任何人都可以帮助解决如何在CAKEPHP 3.0查询构建器中实现此目的吗?

1 个答案:

答案 0 :(得分:1)

最简单的解决方案如下

$cond_arr = [
    'VehicleBrandModels.status' => 1, 
    'OR' => [
        ['overall_rating >' =>  0, 'overall_rating <' => 2],
        ['overall_rating >=' => 2, 'overall_rating <' => 4],              
        ['overall_rating >=' => 4, 'overall_rating <=' => 5]
    ]
];

有一种更“蛋糕”的方式,如果我有时间,我会发布它。

但请注意,从我看到的所有OR条件重叠,你可以简单地做

 $cond_arr = [
    'VehicleBrandModels.status' => 1, 
    'overall_rating >' =>  0, 
    'overall_rating <=' => 5
];

编辑:这里所说的是使用查询表达式的更多蛋糕方式

$query->where(function($exp, $q) {
    $exp = $exp->eq('VehicleBrandModels.status', 1);
    $conditions1 = $exp->and_([])
        ->gt('overall_rating ', 0)
        ->lte('overall_rating ', 2);
    $conditions2 = $exp->and_([])
        ->gt('overall_rating ', 2)
        ->lte('overall_rating ', 4);
    $conditions3 = $exp->and_([])
        ->gt('overall_rating ', 4)
        ->lte('overall_rating ', 5);
    $orConditions = $exp->or_([$conditions1, $conditions2, $conditions3]);
    $exp->add($orConditions);
    return $exp;
});

仍有一些条件重叠