简体   繁体   中英

How to get average ratings in laravel using jquery

I have two table Users and ratings,.A User can give rating to consultant, My Rating table look like below

 User_id | consultant_id | rating
 ---------------------------------      
        1           1        2
 ---------------------------------
        2           1        3
 ---------------------------------
        3           1        1
 ---------------------------------
        4           1        1

This how my table looks like

My controller:

public function searchConsultants(Request $request)
{
         $location = $request->get('location');
         $data = Consultant::where('location','LIKE','%'.$location.'%')->with('ratings')->get();
         return response()->json($data);
}

Response Im get from searchConsultants method

[{"id":1,"cunsultant_name":"Manjunath Mj",
     "contact_number":"9035206471",
     "location":"Delhi",
     "department_id":1,09:00:51",

       "ratings":[{
           "id":1,"customer_id":1,"consultant_id":1,"rating":4, 
           "id":2,"customer_id":2,"consultant_id":1,"rating":2, 
           "id":3,"customer_id":3,"consultant_id":1,"rating":1, 
           "id":4,"customer_id":4,"consultant_id":1,"rating":5, 
    }]
}]      

Im using ajax get method to diplay the data, here is my js file

$.each(data, function(index) {
   str +="<tr><td>"+data[index].id+"</td>
  <td>"+data[index].cunsultant_name+"</td>
  <td>"+data[index].contact_number+"</td>
  <td>"+data[index].ratings[index].rating_for_manager+"</td><td>"+data[index].location+"</td></tr>";
}); 

When I click search consultant button I should get consultant details with average ratings.

You can get the avg rating from the query in your Controller's searchConsultants method.

Change your query to this (this should give you average rating of each consultant matching with the search criteria):

$data = Consultant::select('consultants.*', DB::raw('avg(rating)') )

->where('location','LIKE','%'.$location.'%')

->join('ratings', 'ratings. consultant_id', '=', 'consultants.id')

->groupBy('consultant_id')->get();

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