【问题标题】:Laravel eloquent query with sum of related tableLaravel 雄辩的查询与相关表的总和
【发布时间】:2019-02-13 12:15:44
【问题描述】:

我有一个 usersposts 表,其中包含 user_idpost_views 列。 在 post_views 中,我保留了帖子显示次数的信息。

现在,在查询中,我希望 user 获得他所有帖子的 post_views 总和。

我试着做这样的事情:

User::where(['id'=>$id])->with('posts')->get();

在我定义的模型中:

public function posts()
    {
        return $this->hasMany('App\Models\Post')->sum('post_views','AS','totalViews');
    }

但没有成功。

怎么做?

谢谢

【问题讨论】:

    标签: laravel eloquent


    【解决方案1】:

    您可以使用修改后的withCount()

    public function posts()
    {
        return $this->hasMany('App\Models\Post');
    }
    
    $user = User::withCount(['posts as post_views' => function($query) {
        $query->select(DB::raw('sum(post_views)'));
    }])->find($id);
    // $user->post_views
    

    【讨论】:

    • 工作绝对完美。:) 非常感谢。
    【解决方案2】:

    你可以使用

    User::withCount('posts')->find($id)

    在响应中获取 ID 为 $idposts_count 属性的用户

    我不完全确定 ->sum('game_plays','AS','totalVies'); 的意图是什么 - 如果需要,您需要添加更多上下文

    关于您显示的代码,只需添加一些内容:无需通过 id 查询,最后使用 where + get() 将使您查询集合。如果您想获得单个结果,请在按 id 搜索时使用 find

    【讨论】:

    • 对不起,这个 (->sum('game_plays','AS','totalVies');) 是错误的复制和粘贴。应该是:->sum('post_views','AS','totalVies')。但是你的代码不算我想要的。您的代码,计算用户的记录数,因此结果属于用户的帖子数。我需要计算属于用户的所有帖子的总浏览量。
    猜你喜欢
    • 2019-06-27
    • 2021-06-17
    • 2016-07-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-09
    • 1970-01-01
    • 2018-01-26
    相关资源
    最近更新 更多