jeudi 21 novembre 2019

Laravel: Get all contestants of audition along with their votes

I have Laravel Eloquent model with table structure

-contestants
  --id
-auditions
  --id
-audition_contestant
  --audition_id
  --contestant_id
-audition_votings
  --audition_id
  --contestant_id
  --vote

Contestant belongs to Many Auditions and Audition can have Many Contestants.

Whenever certain contestant of certain audition is voted, audition_votings table is used to store it.

I need to get all contestants of certain audition along with total vote that is being calculated from audition_votings table. for example endpoints will be

/audition/{id}/contestants

I have tried relation on Audition model like this

    public function contestantVotes(){
        return $this->belongsToMany('App\Contestant','audition_votings','audition_id','contestant_id')
            ->selectRaw('contestants.*,sum(vote) as vote')
            ->withTimestamps()
            ->groupBy('contestant_id')
            ->orderByDesc('vote');
    }

But this code will only show contestants if contestants is present on audition_votings but what i want is contestants on audition_contestant along with their total votes.

Raw sql query will also work.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire