laravel中比较常规的列表查询:
/**
* 活动列表
* @param Request $request
* @return \Illuminate\Http\JsonResponse
*/
public function getActiveList(Request $request,UrlManager $urlManager)
{ $name = $request->get('name'); //活动标题
$start_time = $request->get('start_time'); //活动开始时间
$author_user_name = $request->get('author_user_name'); //活动发布者
$active_classify_id = $request->get('active_classify_id'); //活动分类 $limit = (int) $request->get('limit', 15);
$offset = (int) $request->get('offset', 0); $query = ActiveContent::with(['user'])
->when($active_classify_id, function ($query) use ($active_classify_id) {
$query->where('active_classify_id', $active_classify_id);
})
->when($name, function ($query) use ($name) {
$query->where('name', 'like', sprintf('%%%s%%', $name));
})
->when($start_time, function ($query) use ($start_time) {
$query->where('created_at', '>=', $start_time);
})
->when($author_user_name, function ($query) use ($author_user_name) {
return $query->whereHas('user', function ($query) use ($author_user_name) {
return $query->where('name', 'like', '%'.$author_user_name.'%');
});
}); $total = $query->count('id');
$items = $query->limit($limit)
->offset($offset)
->orderBy('weight', 'desc')
->orderBy('id', 'desc')
->paginate()->toArray(); foreach($items['data'] as $key=>$value){
//获取活动封面
$active_face = ActiveContent::with('faces')->where('id', $value['id'])
->select('face', 'id')->get()->keyBy('id'); $items['data'][$key]['face']=(isset($active_face[$value['id']]) && $active_face[$value['id']]->faces) ? $urlManager->make($active_face[$value['id']]->faces->file) : ''; } return response()->json($items, 200, ['x-ad-total' => $total]); }