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 App的会员连续扣费
  • ¥15 不同数据类型的特征融合应该怎么做
  • ¥15 用proteus软件设计一个基于8086微处理器的简易温度计
  • ¥15 用联想小新14Pro
  • ¥15 multisim中关于74ls192n和DSWPK开关仿真图分析(减法计数器)
  • ¥15 基于8255的交通灯设计
  • ¥15 w3wp,exe 中发生未处理的 Microsoft ,NETFramework 异常。
  • ¥20 C51单片机程序及仿真(加减器)
  • ¥15 AQWA | 水动力分析 二阶波浪力
  • ¥15 c语言题目:成绩管理系统