vendredi 13 septembre 2019

find max count of nested though relationship

This is my Polling system models and relations

Poll
id --- title
    hasManyQuestions();
Question
id --- poll_id  --- title 
 hasManyOptions();
 belongstoPoll();

Option
id --- option_id --- title
 hasManyvotes();
 belongstoQuestion();

Vote
id --- user_id --- option---id
blongsToOption();

I want this query

and this is only return to me count for each options i need sum(count(options.result)) for each question

something like $question->count('votes')

$data['poll'] = Poll::where('id' , $id)
            ->where('status' , 'on')
            ->with('user')
            ->with(['questions' => function($query){

                $query->with(['options' => function($newQuery){
                    $newQuery->withCount('votes');

                }]);

            }])

            ->first();

anyone can help me?

for this data

questions[id:1 ,poll_id:10 , title:defender players]
options[id:1 , question_id:1 , title:Ramos]
options[id:2 , question_id:1 , title:Pique]
options[id:3 , question_id:1 , title:Ferdinand]

questions[id:2 ,poll_id:10 , title:attacker players]
options[id:4 , question_id:2 , title:Messi ]
options[id:5 , question_id:2 , title:Ronaldo]
options[id:6 , question_id:2 , title:Zlatan]

Votes[id:1 ,option_id: 6 , user_id:103]; //option 6 blongs to question 1
Votes[id:2 ,option_id: 6 , user_id:13]; //option 6 blongs to question 1
Votes[id:3 ,option_id: 2 , user_id:19]; //option 2 blongs to question 2
Votes[id:4 ,option_id: 1 , user_id:103] //option 1 blongs to question 2
Votes[id:5 ,option_id: 3 , user_id:1300]; //option 3 blongs to question 2
Votes[id:6 ,option_id: 2 , user_id:1980]; //option 2 blongs to question 2

so i want the query to get

question with id 1 has 4 votes

question with id 2 has 2 votes



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/32Eeuu7
via IFTTT

Aucun commentaire:

Enregistrer un commentaire