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

问题描述 投票:1回答:2

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

而现在,在查询中我希望用户获得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
2个回答
4
投票

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

0
投票

您可以使用

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

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

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

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

© www.soinside.com 2019 - 2024. All rights reserved.