【问题标题】:laravel add multiple where and or wherelaravel 添加多个 where 和 or where
【发布时间】:2025-12-20 22:10:12
【问题描述】:
[
    [ 
        [ 
        'condition1', 
        'value1',
        ],
        [ 
        'condition2', 
        'value2',
        ],
        [ 
        'condition3', 
        'value3',
        ],
    ], 
    [ 
    'condition4', 
    'value4',
    ],
    [

    ]

]

我正在尝试使用值 1、值 2、值 3 在“或”条件下和值 4 在“和”条件下构建查询构建器

对于前两个数组,我可以得到我需要的结果

$result = DB::table('table')
   ->where(function($query) use($value1) {
      $query->where('condition1', $value1) // and condition
            ->orWhere('condition2', $value2) // rest or in or condition
            ->orWhere('condition3', $value3)
   })
   ->where('condition4', $value4)
   ->get();

但阵列将继续进行。数组索引 0 内处于“和”条件和 a;;其他索引或条件

我试过了

foreach($values as $value){ //
  $result->where(function ($qry) use ($value) { 
    foreach($value as $index=>$val){ 
    $qry->when($index==0),function($qyr){
       $qry->where();
    }
    },function($qry){
       $qry->orwhere();
    }
  });

}  

我可以添加任何更好的解决方案或改进吗?

【问题讨论】:

    标签: mysql laravel loops eloquent


    【解决方案1】:

    您不应该在分组查询中使用 condition3。通常它应该是这样的:

    $result = DB::table('table')->where(function($query) use($value1, $value2) {
      $query->where('condition1', $value1) // where condition1
            ->orWhere('condition2', $value2); // or where condition2            
    })->Where('condition3', $value3) // And where condition3
    ->get();
    

    【讨论】:

      最近更新 更多