2016-12-12 10 views
1

Ich habe nächste Modelle:Laravel 5.3 bekommen belongsToMany und zählt Dreh

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 - Pivot-Tabelle hat Struktur: id, poll_id, participant_id. Ich brauche nächste Tabelle anzuzeigen:

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

Count Abstimmung Pivot-Tabelle poll_results bekommen. Hilfe bitte, schreibe Abfrage.

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

Antwort

0

Möglicherweise möchten Sie withCount() Methode verwenden.

Wenn Sie die Anzahl der Ergebnisse aus einer Beziehung zu zählen, ohne sie tatsächlich Laden Sie die withCount Methode verwenden, die eine FINDET {Beziehung} _count Spalte auf dem resultierenden Modelle

Ihre Anfrage würde aussehen wie diese:

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

Dies wird neue Eigenschaft Ergebnisse genannt polls_count

+0

Diese Rückkehr TEILNEHMER hinzufügen ts count (Teilnehmerliste abrufen) Column Count vote - muss aus der poll_results-Tabelle abgerufen werden. –