Laravel雄辩的查询与相关表的总和 [英] Laravel eloquent query with sum of related table

查看:88
本文介绍了Laravel雄辩的查询与相关表的总和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个表 users posts ,其中有 user_id post_views 列。
post_views 中,我保留了帖子显示多少次的信息。

I have a table users and posts with columns user_id and post_views. In post_views I keep information how many times post was display.

现在,在查询中,我想得到用户,其所有帖子的总和为 post_views

And now, in query I would like to get user with sum of post_views all his posts.

我尝试执行以下操作:

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

在模型中,我定义为:

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

但没有成功。

该怎么做?

谢谢

推荐答案

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

You can use a modified 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

这篇关于Laravel雄辩的查询与相关表的总和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆