在Laravel中对集合执行sum()

时间:2014-06-08 09:14:37

标签: php laravel aggregate-functions eloquent relationship

我有一个基本论坛系统的应用程序,用户可以在这里使用#34;喜欢"一个主题多次。我的模型扩展了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);
}

然而,由此我收到错误声明:

  

未知专栏' ideas.id'在' where子句' (SQL:选择sum(votes)   来自votes的汇总votesidea_id = ideasid和   idea_id = 1)`

2 个答案:

答案 0 :(得分:0)

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

$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:如果它不起作用,请发布您的模型关系方法。

答案 1 :(得分:0)

我设法让它工作,虽然我不确定我喜欢这种方法。我很想知道是否有人知道这样做的更好方法......

基本上,我使用我的关系过滤()投票,然后在过滤的集合上使用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'));
}