dongtiao2105 2017-08-20 01:52
浏览 30

如何用CakePHP 3.x查询构建器表达OR条件?

I am trying to build a query in cakephp 3.X with the following structure : A and B and C and [D or E] where A,B, C, D, E contains an array of values joined with OR conditions like

$schools = $schools->where(['A  IN' => $arrayOfAOptions]), 
$schools = $schools->where(['B IN' => $arrayOfBOptions]),
$schools = $schools->where(['C IN' => $arrayOfCOptions])

// want this to be firstly joined with OR before joining other conditions with AND
$schools = $schools->where(['D IN' => $arrayOfCOptions]) 
//or
$schools = $schools->where(['E IN' => $arrayOfCOptions])

the problem here is that , I could not get fields D and E to be isolated as OR and join others with AND

in cakephp 2, i managed to achieve it with the following codes

$queryConditions = array(
  'or'=> array_merge(
    array(
      'School.D' =>  $this->Session->read('conditions.D')
    ), 
    array(
      'School.E' => $this->Session->read('conditions.E')
    )
  )
);

before merging it to the rest on the conditions Any help would be appreciated

  • 写回答

1条回答 默认 最新

  • doupai8095 2017-08-20 11:14
    关注

    You can use the same style as in CakePHP 2.x, ie pass your conditions nested under the OR key. You can also wrap this in a single where() call.

    $schools->where([
        'A IN' => $arrayOfAOptions,
        'B IN' => $arrayOfBOptions,
        'C IN' => $arrayOfCOptions,
        'OR' => [
            'D IN' => $arrayOfDOptions,
            'E IN' => $arrayOfEOptions
        ]
    ]);
    

    You could also use orWhere(), but it has been deprecated lately as its behavior is a kinda fragile.

    Finally, you can use expressions to create complex conditions. The or_() expression method can be used to create OR conditions:

    $schools->where(function ($expr) use ($arrayOfAOptions, $arrayOfBOptions) {
        return $expr->or_([
            'A IN' => $arrayOfAOptions,
            'B IN' => $arrayOfBOptions,
        ]);
    });
    

    See also Cookbook > Database Access & ORM > Query Builder > Advanced Conditions

    评论

报告相同问题?

悬赏问题

  • ¥15 latex投稿显示click download
  • ¥15 请问读取环境变量文件失败是什么原因?
  • ¥15 在若依框架下实现人脸识别
  • ¥15 网络科学导论,网络控制
  • ¥100 安卓tv程序连接SQLSERVER2008问题
  • ¥15 利用Sentinel-2和Landsat8做一个水库的长时序NDVI的对比,为什么Snetinel-2计算的结果最小值特别小,而Lansat8就很平均
  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?