我有一张桌子users and posts有柱子user_id and 帖子浏览量.
In 帖子浏览量我保留帖子显示次数的信息。
现在,在查询中我想得到user总和为帖子浏览量他的所有帖子。
我尝试做这样的事情:
User::where(['id'=>$id])->with('posts')->get();
在我定义的模型中:
public function posts()
{
return $this->hasMany('App\Models\Post')->sum('post_views','AS','totalViews');
}
但没有成功。
怎么做?
谢谢
您可以使用修改后的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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)