我正在使用laravel并使用过滤器进行查询,我不知道该怎么做但我有一个想法,这就是我想要的。
$wheresMethodsChain;
$type = "house";
$model = "paper";
// sometimes it could be empty
$size = "";
if ($type != "") {
// add to chain to call later
add_to_my_chain_of_wheres( $wheresMethodsChain , ->where('type',$type) );
// wheresMethodsChain = ->where('type',$type)
}
if ($model != "") {
add_to_my_chain_of_wheres( $wheresMethodsChain , ->where('model',$model) );
// wheresMethodsChain = ->where('type',$type)->where('model',$model)
}
if ($size != "") {
add_to_my_chain_of_wheres( $wheresMethodsChain , ->where('size',$size) );
// wheresMethodsChain = ->where('type',$type)->where('model',$model)
}
// the final chain should be something like this, only two because the "$size" variable is empty
// ->where('type',$type)->where('model',$model)
// Finally add the chain of wheres at the end of my query
$regs = DB::table('mytable')->paginate(10)->wheresMethodsChain;
感谢您的帮助
答案 0 :(得分:1)
这就是你要做的:
$query = DB::table('mytable');
if($type){
$query = $query->where('type', $type);
}
if($model){
$query = $query->where('model', $model);
}
if($size){
$query = $query->where('size', $size);
}
$results = $query->paginate(10);
答案 1 :(得分:1)
另一种可能的解决方案。如果你总是要使用=
运营商,比如...
$query->where('something', $something)
然后,您可以尝试这样的事情:
$data = array_filter(compact('type', 'model', 'size'));
$results = DB::table('mytable')->where($data)->paginate(10);