2016-12-12 6 views
1

を数える: - :ID、poll_id、participant_idLaravel 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ピボットテーブルを構造を有しています。ピボットテーブルにpoll_resultsを取得

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

カウント投票: は、私は次のテーブルを表示する必要があります。 ヘルプを書いてください。

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

答えて

0

withCount()メソッドを使用します。

あなたが実際にあなたがあなたの結果のモデル

あなたのクエリに{関連} _count列を配置しますwithCount方法を、使用することができ、それらをロードすることなく関係からの結果の数をカウントしたい場合この1のようになります。

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

これは、この戻りparticipan polls_count

+0

と呼ばれる結果に新しいプロパティを追加しますts count(参加者テーブルを取得)。列数投票 - poll_resultsテーブルから取得する必要があります。 –

関連する問題