Laravel eloquent 查询与相关表的总和 [英] Laravel eloquent query with sum of related table
本文介绍了Laravel eloquent 查询与相关表的总和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个表 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('AppModelsPost')->sum('post_views','AS','totalViews');
}
但没有成功.
怎么做?
谢谢
推荐答案
您可以使用修改后的 withCount()
:
You can use a modified withCount()
:
public function posts()
{
return $this->hasMany('AppModelsPost');
}
$user = User::withCount(['posts as post_views' => function($query) {
$query->select(DB::raw('sum(post_views)'));
}])->find($id);
// $user->post_views
这篇关于Laravel eloquent 查询与相关表的总和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文