Laravel雄辩查询与相关表的总和

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Laravel雄辩查询与相关表的总和相关的知识,希望对你有一定的参考价值。

我有一个表用户和帖子,其中包含user_id和post_views列。在post_views中,我保留信息显示的帖子数量。

而现在,在查询中我希望用户获得post_views的所有帖子。

我尝试过这样的事情:

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

在我定义的模型中:

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

但没有成功。

怎么做?

谢谢

答案

你可以使用修改后的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
另一答案

您可以使用

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

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

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

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

以上是关于Laravel雄辩查询与相关表的总和的主要内容,如果未能解决你的问题,请参考以下文章