说我有2个查询生成器:
$builderA = User::where("happiness", ">", 5);
$builderB = User::where("color", "blue");
除了键入一个新的构建器之外,还有什么方法可以组合这两个构建器,从而产生如下所示的构建器?
$combined = User::where("happiness", ">", 5)->where("color", "blue");
答案 0 :(得分:2)
可以。
$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();
$queryBulider
是Illuminate\Database\Eloquent\Builder
的实例。
答案 1 :(得分:2)
对于更复杂的情况,可以使用tap
和mergeWheres
:
$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添加了几种处理子查询的方法:
答案 2 :(得分:0)
如果要基于任何条件或与任何输入匹配添加查询,则可以尝试以下操作:
$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();