em = $em; parent::__construct(); } protected function configure() { $this->setName('aggregated_rider_rating:load') ->setDescription('Add rider ratings to aggregated rider rating.') ->setHelp('Add rider ratings to aggregated rider rating.'); } protected function execute(InputInterface $input, OutputInterface $output) { // get the ids of all riders $rider_id_list = $this->getRiderIds(); $this->processAggregateRiderRating($rider_id_list); return 0; } protected function processAggregateRiderRating($rider_id_list) { $db = $this->em->getConnection(); $agg_rider_ratings = []; // get all rider ratings per rider $rr_query_sql = 'SELECT rating FROM rider_rating WHERE rider_id = :id'; $rr_query_stmt = $db->prepare($rr_query_sql); foreach ($rider_id_list as $key => $rider_id) { $rr_query_stmt->bindValue('id', $rider_id); $results = $rr_query_stmt->executeQuery(); $total_jos = 0; $total_rating = 0; while ($row = $results->fetchAssociative()) { $rating = $row['rating']; $total_rating = bcadd($total_rating, $rating, 2); // increment number of JOs per rider $total_jos++; } // compute average $agg_rating = 0; if ($total_jos > 0) $agg_rating = bcdiv($total_rating, $total_jos, 2); $agg_rider_ratings[$rider_id] = [ 'agg_rating' => $agg_rating, 'agg_count' => $total_jos, ]; } // create aggregated rider rating $this->createAggregatedRiderRating($agg_rider_ratings); } protected function createAggregatedRiderRating($agg_rider_ratings) { // error_log(print_r($agg_rider_ratings, true)); foreach ($agg_rider_ratings as $key => $data) { // create new AggregatedRiderRating object $obj = new AggregatedRiderRating(); // set fields $obj->setRiderId($key) ->setAggregateRating($data['agg_rating']) ->setAggregateCount($data['agg_count']); // save to database $this->em->persist($obj); } $this->em->flush(); } protected function getRiderIds() { $rider_ids = []; $db = $this->em->getConnection(); $query_sql = 'SELECT id FROM rider'; $query_stmt = $db->prepare($query_sql); $results = $query_stmt->executeQuery(); while ($row = $results->fetchAssociative()) { $rider_ids[] = $row['id']; } return $rider_ids; } }