簡體   English   中英

如何使用jQuery在Laravel中獲得平均評分

[英]How to get average ratings in laravel using jquery

我有兩個表用戶和評分,一個用戶可以給顧問評分,我的評分表如下所示

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

這是我的桌子的樣子

我的控制器:

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

響應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, 
    }]
}]      

我正在使用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>";
}); 

當我單擊搜索顧問按鈕時,我應該獲得具有平均評分的顧問詳細信息。

您可以在Controller的searchConsultants方法中從查詢中獲得平均評級。

將查詢更改為此(這應為您提供與搜索條件匹配的每個顧問的平均評分):

$ data =顧問::: select('consultants。*',DB :: raw('avg(rating)'))

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

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

- > GROUPBY( 'consultant_id') - >獲得();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM