0

我正在尝试使用具有复杂嵌套 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 查询生成器中实现这一目标吗?

4

1 回答 1

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;
});

仍有一些条件重叠

于 2018-05-08T12:32:57.743 回答