2016-12-12 29 views
1

我旁邊型號:Laravel 5.3得到belongsToMany和計數旋轉

class Polling extends Model 
{ 
    /** 
    * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany 
    */ 
    public function participants() 
    { 
     return $this->belongsToMany(Participant::class, 'participant_poll', 'poll_id'); 
    } 

    /** 
    * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany 
    */ 
    public function results() 
    { 
     return $this->belongsToMany(Participant::class, 'poll_results', 'poll_id'); 
    } 
} 

class Participant extends Model 
{ 
    public function polls() 
    { 
     return $this->belongsToMany(Polling::class); 
    } 

    public function results() 
    { 
     return $this->belongsToMany(Polling::class); 
    } 

} 

poll_results - 透視表具有的結構:ID,poll_id,participant_id。 我需要查看下錶:

 
№|participant.name|Count vote| 
1|Mike   |15  | 
2|................|10  | 
.............................. 

計票獲得的數據透視表poll_results。 請幫忙寫下查詢。

$poll = Polling::first(); 
$poll->participants()->get(); 

回答

0

您可能想要使用withCount()方法。

如果你要計算從一個關係結果的數量,而無需實際加載它們,你可以使用withCount方法,這將放置{關係} _count列上你的最終模型

您查詢看起來像這樣的:

Participant::withCount('polls')->get(); 

這將增加新的屬性稱爲結果polls_count

+0

這回participan ts計數(獲得參與者表)。列數投票 - 需要從poll_results表中獲取。 –