2014-06-08 27 views
1

我有一個基本論壇系統的應用程序,用戶可以多次「喜歡」一個主題。我的模型延伸口才,我想拿到票的用戶具有特定主題的總和......基本上,我試圖完成這樣的:在Laravel的集合上執行sum()

$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子句'(SQL

未知列 'ideas.id':SELECT SUM(votes) 作爲骨料從votes其中votesidea_id = ideasididea_id = 1)`

回答

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:如果它不」那麼請發佈你的模型的關係方法。

+0

你可以在這裏看到我的關係:http://www.laravelsd.com/share/8jQRWl – user1960364

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')); 
}