Laravel 计数不起作用,有任何支持吗?

我正在尝试在 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

}


PIPIONE
浏览 113回答 2
2回答

噜噜哒

通过在关系上添加括号,您可能会发现使用查询构建器获取计数而不是关系/集合更容易。你甚至可以跳过三元组。$user->downloads = $user->downloads()->count('id');$user->likes = $user->likes()->count();$user->reads = $user->reads()->count();$user->dislikes = $user->dislikes()->count();

红颜莎娜

我建议使用withCount(). 检查文档$user = User::find($req->username)->withCount('likes')->get(); $user->likes_count // this will give you user's like count
打开App,查看更多内容
随时随地看视频慕课网APP