我有两个表用户和评级,.A用户可以给顾问评分,我的评级表如下所示
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);
}
响应我来自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>";
});
当我点击搜索顾问按钮时,我应该获得平均评分的顾问详细信息。
答案 0 :(得分:0)
您可以在Controller的searchConsultants方法中从查询中获得平均等级。
将您的查询更改为此(这应该为您提供与搜索条件匹配的每位顾问的平均评分):
$ data =顾问:: select('顾问。*',DB :: raw('avg(rating)'))
- 化合物其中(。 '位置', 'LIKE', '%' $位置 '%')
- &gt;加入('评分','评级.consultant_id','=','consultants.id')
- &GT; GROUPBY( 'consultant_id') - &GT;得到();