在Laravel中对集合执行sum()


Performing a sum() on a collection in Laravel

我有一个带有基本论坛系统的应用程序,用户可以多次"点赞"一个主题。我的模型扩展了Eloquent,我试图获得用户对特定主题的投票总数。。。基本上,我正在努力完成这样的事情:

$votes = Auth::user()
    ->votes->has('topic_id', '=', $topic->id)
    ->sum('votes');

然而,在执行此操作时,我会得到以下错误。。。

调用非对象上的成员函数sum((

我也试过

public function show($forumSlug, $topicSlug)
{
    $topic = Topic::whereSlug($topicSlug)->first();
    $votes = Topic::whereHas('votes', function ($q) use ($topic)
    {
        $q->where('topic_id', '=', $topic->id)->sum('votes');
    });
    dd($votes);
}

然而,我收到一个错误:

"where子句"中的未知列"ideas.id"(SQL:select sum(votes(作为来自CCD_ 2的聚合,其中CCD_。idea_idideasididea_id=1(`

你可以尝试这样的事情(不确定你的关系,但试一试(:

$topic = User::with(array('topics' => function ($query) use ($topic_id) {
    // $query = Topic, so it's: Topic::with('votes')
    $query->with('votes')->where('topics.id', $topic_id);
}))->find(Auth::user()->id)->topics->first();
// Count of total votes
dd($topic->votes->count());

p/S:如果不起作用,请发布您的模型的关系方法。

我设法让它工作起来,尽管我不确定我是否喜欢这种方法。我很想知道是否有人知道更好的方法。。。

基本上,我使用我的关系来过滤((投票,然后对过滤后的集合使用sum((。

public function show($forumSlug, $topicSlug)
{
    $userId = is_null(Auth::user()) ? false : Auth::user()->id;
    $topic = Topic::whereSlug($topicSlug)->first();
    $votes = $topic->votes->filter(function ($votes) use ($userId)
    {
        return $votes->user_id == $userId;
    })->sum('votes');
    return View::make('forums.topics.show', compact('topic', 'votes'));
}