有没有办法结合 Laravel 查询生成器条件?

Is there a way to combine Laravel query builder conditions?

假设我有 2 个查询构建器:

$builderA = User::where("happiness", ">", 5);
$builderB = User::where("color", "blue");

除了输入新的构建器之外,还有什么方法可以组合这 2 个构建器,生成如下所示的构建器?

$combined = User::where("happiness", ">", 5)->where("color", "blue");

是的,你可以。

$combinedUsers = User::where([
   ["happiness", ">", 5], 
   ["color" => "blue"]
])->get();

$combinedUsers = User::where([
   ["happiness", ">", 5], 
   ["color", "=", "blue"]
])->get();

在你的情况下你必须使用 orWhere

// one request in db
$combinedUsers = User::where("happiness", ">", 5)->orWhere("color", "blue")->get();

// filter in Collection instance
$happyUsers = $combinedUsers->where("happiness", ">", 5); 
$blueUsers = $combinedUsers->where("color", "blue"); 

你也可以使用

$queryBulider = User::newQuery();
$queryBulider->...->get();

$queryBuliderIlluminate\Database\Eloquent\Builder 的实例。

对于更复杂的情况,您可以使用 tapmergeWheres:

$where = User::where('a', 1)->where('b', '>', 2)->where('c', '<', 2)->where('d', '<>', 2);

$combined = User::where('e', 5)->tap(function (Builder $builder) use ($where) {
    $builder->mergeWheres($where->wheres, $where->getBindings());
});

Laravel 5.6 添加了几种处理子查询的方法:

如果你想添加基于任何条件或与任何输入匹配的查询,那么你可以试试这个:

$combinedUsers = User::query();
if(YourCondition){
    $combinedUsers = $combinedUsers->where("happiness", ">", 5);
}
if(YourCondition){
    $combinedUsers = $combinedUsers->where("color","blue");
}
if(YourCondition){
    $combinedUsers = $combinedUsers->orderBy("color");
}
$combinedUsers = $combinedUsers->get();