Search code examples
phpmysqllaravellaravel-5laravel-5.3

Get average with nested relationship belongs to in laravel


I want to ask for you. hopefully my problem will be quickly resolved.

I have 3 tables consist of :

ads

  • id

  • title_ads

transaction

  • id

  • transaction_id

  • id_ads

rating

  • id
  • transaction_id
  • rating_value

relationship :

ads to transaction is has many

transaction to rating is belongs to

I want to ask this, how to get avg rating value from table ads? I am confused, because I think to get avg rating maybe use hasManyThrought but in this case, There is relationship belongsTo. hwo to solved it? Thank you very much :)


Solution

  • Define a hasManyThrough relation in your Ad model

    class Ad extends Model
    {
        /**
         * Get all ratings of an Ad.
         */
        public function ratings()
        {
            return $this->hasManyThrough('App\Rating', 'App\Transaction');
        }
    }
    

    Now you can get the ratings in your controller with the Ad model and the ratings relation

    public function getRatingsAverage()
    {
        // Fetch a single ad (or remove the find and get multiple)
        $ad = Ad::where('id', 1)->with('ratings')->get();
    
        // write average logic here...
    
        // could be something like this:
        $total_rating = 0;
    
        foreach($ad->ratings as $rating) {
            // loop through all the ratings of the ad and add the value to the total rating
            $total_rating = $total_rating + $rating->value;
        }
    
        // divide the total rating by the amount of ratings to get the average
        $average = $total_rating / count($ad->ratings);
    }