我有两个表用户和评级,.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方法来显示数据,这是我的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>";
});
当我点击搜索顾问按钮,我应该得到平均评分顾问的详细信息。
发布于 2017-07-21 03:43:51
您可以从Controller的searchConsultants方法中的查询中获得avg评级。
将查询更改为此(这将给出与搜索标准匹配的每个顾问的平均评分):
$data =顾问::select(‘咨询人。*’,DB::raw(‘avg(评级)’)) ->where('location','LIKE',‘%’,$location,‘%’) ->join(“评级”、“评级.顾问_id”、“=”、“consultants.id”) ->groupBy('consultant_id')->get();
https://stackoverflow.com/questions/45236475
复制相似问题