RafaelMunoznl
8 months ago

Is there an alternative and more efficient method that loop through a collection?

Posted 8 months ago by RafaelMunoznl

I have following model structure

Author has many Events Event has many Reviews (kind of Rating) Review has many Likes

I want to show in the authors index view the average stars of each author besides his name. Something like:

  • author 1 (2 stars)
  • author 2 (5 stars) ...

So I need to do two steps:

  • get the average in each single event belonging to one author looping through the reviews of each event
  • calculate the average rating of the author

For the first step I need to loop twice

    foreach ($author->events as $event) {

        foreach ($event->reviews as $review) {

            if ($review->rating > 0) {

                if($review->rating == 0) { $stars = 0; }
                elseif($review->rating == 1) { $stars = 20; }
                elseif ($review->rating == 2) { $stars =40;}
                elseif ($review->rating == 3) { $stars =60;}
                elseif ($review->rating == 4) { $stars =80;}
                else { $stars = 100;}        
                $review['stars'] = $stars;
                array_push($a, $stars);

                $event['avrRating'] = $avrRating = array_sum($a)/count($a);
            } else {
                $event['avrRating'] = 0;
            }
        }
    }

It works for 10 authors with three events each, but once I tested with 400 authors, 20 events each, 30 reviews each events and 40 likes esach review I got the following message:

"Memory exhausted"

My question is:

Is there any way more efficient than loop twice? I tried with hasManyThrough relations but same results.

If I need to get the likes of an author, things get worse

Please sign in or create an account to participate in this conversation.