我正在用laravel 5.2开发一个项目。我有一个问题,在我的PostController中,我接受一个参数is_paginated,它是一个整数。如果为0,则表示查询所有帖子。如果为1,则表示使用分页查询。除了这个参数之外,我还接受许多额外的参数,并根据它们的值来决定是否添加查询约束。例如,用户可以传递add_time来查询特定日期生成的帖子。因此,在我的控制器中,我现在写道:
public function getPosts(Request $request){
$isPaginated = $request->input('is_paginates');
if($isPaginated){
/*
*According to additional arguments to add query constraints or not, then
*use paginate method.
*/
.....->paginate(10);
}else{
/*
*According to additional arguments to add query constraints or not, then
*use get method.
*/
......->get();
}
}所以你可以看到,我写了两次add constraints代码,如果有很多约束需要添加,它看起来非常臃肿。那么,有没有其他方法可以做到这一点呢?
发布于 2017-07-12 03:41:05
你可以在这里使用方法链接的奇妙之处:
var $a = \App\Class::where("c",1);
if($offset = $request->input("offset")){
$a = $a->skip($offset);
}
if($limit = $request->input("limit")){
$a = $a->take($limit);
}
if($request->input("is_paginated")){
$a = $a->paginate(10);
}
$a_vals = $a->get();https://stackoverflow.com/questions/44895647
复制相似问题