laravel 查询
Posted 心之所依
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了laravel 查询相关的知识,希望对你有一定的参考价值。
public function recommends(Request $request) { // $sort = $request->query(‘sort‘); $userId = $request->query(‘userId‘); $email = $request->query(‘email‘); $name = $request->query(‘name‘); $phone = $request->query(‘phone‘); // $role = $request->query(‘role‘); $perPage = $request->query(‘perPage‘, 1); $showRole = $request->has(‘show_role‘); $datas = [ ‘page‘ => [], ‘roles‘ => ‘‘, ‘lastPage‘ => 0, ‘perPage‘ => $perPage, ‘total‘ => 0, ]; if ($showRole) { $datas[‘roles‘] = Role::all(); } // user id if ($userId && $users = UserRecommended::where(‘user_id‘, $userId)->paginate($perPage)) { $datas[‘page‘] = $users->map(function ($user) { $user->setHidden([]); $user->load(‘user‘); return $user->user; }); return response()->json($datas)->setStatusCode(200); } $sourceUsers = []; if ($name || $email || $phone) { $sourceUsers = User::when($name, function ($query) use ($name) { return $query->where(‘name‘, ‘like‘, "%{$name}%"); }) ->when($email, function ($query) use ($email) { return $query->where(‘email‘, ‘=‘, $email); }) ->when($phone, function ($query) use ($phone) { return $query->where(‘phone‘, ‘like‘, "%{$phone}%"); }) ->select(‘id‘) ->get() ->pluck(‘id‘); } $users = UserRecommended::with(‘user‘) ->when($sourceUsers, function ($query) use ($sourceUsers) { return $query->whereIn(‘user_id‘, $sourceUsers); }) ->paginate($perPage); $list = $users->getCollection(); $datas[‘page‘] = $list->map(function ($user) { $user->user->setHidden([]); return $user->user; }); $datas[‘lastPage‘] = $users->lastPage(); $datas[‘perPage‘] = $perPage; $datas[‘total‘] = $users->total(); $datas[‘currentPage‘] = $users->currentPage(); return response()->json($datas)->setStatusCode(200); }
以上是关于laravel 查询的主要内容,如果未能解决你的问题,请参考以下文章
需要一种有效的方法来避免使用 Laravel 5 重复代码片段