相关的$ query->但是“选择属性为”

时间:2017-11-10 19:18:21

标签: laravel laravel-5 eloquent laravel-5.5

我使用的是Laravel 5.5.13。

我正在尝试获取所有扩展程序,但根据其关系使用某些额外属性。

我的目标是获取此类数据,我正在尝试获取latest_comment_datethumbs_countthumbs_yes_count

[
    {
        "id": 3,
        "name": "Pull Refresh",
        "created_at": "2017-11-10 06:04:44",
        "updated_at": "2017-11-10 06:04:44",
        "latest_comment_date": "2017-11-10 05:46:25",
        "thumbs_count": 10,
        "thumbs_yes_count": 2
    }
]

我试过了:

        return Extension::with([
            'comments' => function($query) { // rename to 'latest_comment_date'
                $query->orderBy('created_at', 'desc')->take(1);
            },
            'thumbs' => function($query) { // rename to 'thumbs_count'
                $query->count();
            },
            'thumbs' => function($query) { // rename to 'thumbs_yes_count'
                $query->where('like', '=', true)->count();
            }
        ])->get();

这给了我这样的数据:

[
    {
        "id": 3,
        "name": "Pull Refresh",
        "created_at": "2017-11-10 06:04:44",
        "updated_at": "2017-11-10 06:04:44",
        "comments": [
            {
                "id": 10,
                "body": "heck ya baby",
                "displayname_id": 2,
                "extension_id": 3,
                "created_at": "2017-11-10 18:31:31",
                "updated_at": "2017-11-10 18:31:31"
            }
        ],
        "thumbs": []
    }
]

请你帮助我“挑选”最重要的东西?

1 个答案:

答案 0 :(得分:2)

为了计算,您应该使用withCount,如下所示:

return Extension::withCount(
                'thumbs', 
                'thumbs as thumbs_yes_count' => function($query) {
                   $query->where('like', '=', true);
               })->get();

参考:Counting related models

要获取最新评论,您应该创建额外的关系:

public function latestComment()
{
   return $this->hasOne(Comment::class)->orderBy('created_at', 'desc');
}

所以整个代码看起来像这样:

return Extension::with('latestComment')->withCount(
                'thumbs', 
                'thumbs as thumbs_yes_count' => function($query) {
                   $query->where('like', '=', true);
               })->get();