我正在尝试在 api 上输出用户详细信息我正在使用 laravel 6 但count给了我意想不到的输出可能是它没有醒来所以我不知道任何人都可以提供帮助 public function userDetails(User $user, Request $req){ $user = $user->find($req->username); if(empty($user))//check if user exists return response()->json(["msg"=>"No user found "],404); $user->profile = empty($user->profile) ? "" : $user->profile->file; $user->downloads = empty($user->downloads) ? 0 : $user->downloads->count('id'); $user->likes = empty($user->likes) ? 0 : $user->likes->count(); $user->reads = empty($user->reads) ? 0 : $user->reads->count(); $user->dislikes = empty($user->dislikes) ? 0 : $user->dislikes->count(); return response()->json($user, 200); }输出{"username": "liberi","firstName": null,"secondName": null,"gender": null,"phone": "0987654321","email": "liberi@gmail.com","created_at": "2020-05-12 21:48:33","updated_at": "2020-05-12 21:48:33","email_verified_at": null,"phone_verified_at": null,"profile": null,"downloads": [],"likes": [ { "id": 1, "book_ISBN": "09876543236", "user_username": "liberi", "created_at": null, "updated_at": null }, { "id": 2, "book_ISBN": "09876543236", "user_username": "liberi", "created_at": null, "updated_at": null }],"reads": [],"dislikes": []}预期输出{"username": "liberi","firstName": null,"secondName": null,"gender": null,"phone": "0987654321","email": "liberi@gmail.com","created_at": "2020-05-12 21:48:33","updated_at": "2020-05-12 21:48:33","email_verified_at": null,"phone_verified_at": null,"profile": null,"downloads": 0,"likes": 2,"reads": 0,"dislikes": 0}
2 回答
噜噜哒
TA贡献1784条经验 获得超7个赞
通过在关系上添加括号,您可能会发现使用查询构建器获取计数而不是关系/集合更容易。你甚至可以跳过三元组。
$user->downloads = $user->downloads()->count('id');
$user->likes = $user->likes()->count();
$user->reads = $user->reads()->count();
$user->dislikes = $user->dislikes()->count();
红颜莎娜
TA贡献1842条经验 获得超12个赞
我建议使用withCount()
. 检查文档
$user = User::find($req->username)->withCount('likes')->get(); $user->likes_count // this will give you user's like count
- 2 回答
- 0 关注
- 112 浏览
添加回答
举报
0/150
提交
取消