lundi 15 octobre 2018

How to get votes with results with percent calculating

In my Laravel 5.7/mysql 5 app I have a table with votes results:

`id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
`vote_item_id` INT(10) UNSIGNED NOT NULL,
`user_id` INT(10) UNSIGNED NOT NULL,
`is_correct` TINYINT(1) NOT NULL DEFAULT '0',
`created_at` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,

where boolean is_correct field is if answer was correct or incorrect. I need to get data on percents of correct answers.

Creating such request

$voteItemUsersResultsCorrect = VoteItemUsersResult::    // Grouped by vote name
getByIsCorrect(true)->
getByCreatedAt($filter_voted_at_from, ' > ')->
getByCreatedAt($filter_voted_at_till, ' <= ')->
getByUserId($filterSelectedUsers)->
getByVote($filterSelectedVotes)->
getByVoteCategories($filterSelectedVoteCategories)->
getByVoteIsQuiz(true)->
getByVoteStatus('A')->
select( \DB::raw('count(vote_item_users_result.id) as count, votes.id, votes.name as vote_name') )->
orderBy('vote_name', 'asc')->
groupBy( 'votes.id' )->
groupBy( 'vote_name' )->
join(\DB::raw('vote_items'), \DB::raw('vote_items.id'), '=', \DB::raw('vote_item_users_result.vote_item_id'))->
join(\DB::raw('votes '), \DB::raw('votes.id'), '=', \DB::raw('vote_items.vote_id'))->
get();

I can get number of correct votes with sql request.

 SELECT count(vote_item_users_result.id)     AS count, votes.id, votes.name     AS vote_name 
    FROM `vote_item_users_result` 
    INNER JOIN vote_items on vote_items.id = vote_item_users_result.vote_item_id 
    INNER JOIN votes  on votes.id = vote_items.vote_id 
    WHERE `vote_item_users_result`.`is_correct` = '1'     AND vote_item_users_result.created_at  > '2018-08-01'      AND vote_item_users_result.created_at  <= '2018-09-22 23:59:59'      AND `votes`.`is_quiz` = '1'     AND `votes`.`status` = 'A' 
    GROUP BY `votes`.`id`, `vote_name` 
    ORDER BY `vote_name` asc 

I know a way to get 2nd similar request with is_correct = '0' and on php side to combine results with percent calculating, but I wonder if that could be done with eloquent in 1 request?

If yes, how ?

Thanks!



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire