2017-07-04 100 views
0

我正在开发一个带有laravel 5.2的项目。我有一个问题,在我的PostController中,我接受一个参数is_paginated,它是一个整数。如果0,则表示查询所有帖子。如果1,则表示使用分页查询。除了这个论点之外,我还接受许多额外的参数,根据它们的值,我确定添加约束来查询与否。例如,用户可以通过add_time来查询在特定日期生成的帖子。所以在我的控制,我现在写的:Laravel 5.2同时使用分页查询和没有分页查询

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码两次,如果有很多限制的增加,它看起来很臃肿。那么还有其他方法可以做到这一点吗?

+0

你有'$请求 - >输入( 'is_paginates')一个错字;' –

回答

0

您可以使用方法的奇迹在这里链接:

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();