简体   繁体   中英

Get Average of rating using lrlaravel eloquent for users

I am getting all user. Each user having multiple rating. I have to find out average of each user rating. Here is my code as below:

$specializationObjModal = DoctorsModal::with('user')->with('doctorSpecialization')->get();
      

      $data = array();
            foreach($specializationObjModal as $dataObj)
            {
                $data[]['user_id'] = $dataObj->user_id;
            }
            $ids = $data;
            $doctor_rating = UserRatings::select('rating','rated_for_user_id')
            ->whereIn('rated_for_user_id', $ids)
            ->where('rating', '<>', '')
            ->get();
           
            $sum = 0;
            $count = 0;
            foreach( $doctor_rating as $rating){
             
                if($rating->rated_for_user_id){
                 
                    $count++;
                    $sum += $rating->rating;
                }
            }
    
           return $avg = $sum / $count;

According to my code I am getting average of all user rating. But I want average of each user Rating according to their Id's because every user having multiple rating and I have to calculate each user rating. Please tell me where I am Wrong.

as you want avg_rating on user collection so

in you User.php

protected $appends = ['avg_rating'];

public function getAvgRatingAttribute()
{
    return UserRatings::where('rated_for_user_id', $this->id)
        ->avg('rating');
}

then in your this collection user object will have new key avg_rating

$specializationObjModal = DoctorsModal::with('user')->with('doctorSpecialization')->get();

ref link

https://laravel.com/docs/8.x/eloquent-serialization#appending-values-to-json https://laravel.com/docs/8.x/queries#aggregates

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM