简体   繁体   English

如何使用jQuery在Laravel中获得平均评分

[英]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 响应Im从searchConsultants方法获取

[{"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 我正在使用ajax get方法来显示数据,这是我的js文件

$.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. 您可以在Controller的searchConsultants方法中从查询中获得平均评级。

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)') ) $ data =顾问::: select('consultants。*',DB :: raw('avg(rating)'))

->where('location','LIKE','%'.$location.'%') - >其中(。 '位置', 'LIKE', '%' $位置 '%')

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

->groupBy('consultant_id')->get(); - > GROUPBY( 'consultant_id') - >获得();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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