【发布时间】:2017-09-10 19:19:42
【问题描述】:
我正在尝试计算相关列的平均评分。关系(1->many)在 Merchant 和 ClientFeedbackReviews 模型之间。
商家模式
[Merchant Model]
::::::::::::::::::::::::::::
public function clientFeedbacks() {
return $this->hasMany('App\ClientFeedbackReviews'); //, 'merchant_id', 'id');
客户反馈评论
:::::::::::::::::::::::::::::::::::::::
class ClientFeedbackReviews extends Model {
protected $table = 'client_feedback_merchants';
public function forMerchant() {
return $this->belongsTo('App\Merchant', 'merchant_id', 'id');
}
public function byClient() {
return $this->belongsTo('App\Clients', 'client_id', 'id');
}
:::::::::::::::::::::::::::::::::::::
我需要获得所有商家的平均评分(作为查询的一部分,我正在计算结果 - 商家根据附近的距离、给定的位置或根据请求数据使用的搜索字符串 em>)
我几乎尝试了在互联网上找到的所有内容,但无法在结果中获得“average_ratings”键值。
这是我尝试过的众多解决方案之一,并粘贴在这里作为示例
/////// query continued //////////
$getMerchantQuery = $getMerchantQuery->with(['clientFeedbacks' => function($query) {
$query->select(DB::raw('AVG( stars) AS average_rating'));
}]);
/////// query continued //////////
这就是我得到的结果——client_feedbacks 的空数组,而我想要average_rating 就在那里。
{
"id": 1,
"user_id": 2,
"company_name": "Best Salon",
"primary_contact": "111111111",
"company_st_address": "Office # 62",
"company_location": "Abc",
"company_city": null,
"company_state": null,
"company_country": null,
"company_zip": null,
"company_lat": "27.9506",
"company_long": "82.4572",
"logo_image": "449cbdf0-12ba-11e7-bc65-b7fa1731e4d5.jpeg",
"is_fav_by_client_count": 3,
"client_feedbacks_count": 1,
"user_details": {
"id": 2,
"email": "client@lir.com"
},
"client_feedbacks": []
}
我们有哪些选项可以计算相关表的平均值?
============ 编辑
但是这会返回结果,但不确定如何在 client_feedbacks 键中获取 AVERAGE。
$getMerchantQuery = $getMerchantQuery->with('clientFeedbacks');
作为
{
"id": 1,
"user_id": 2,
"company_name": "Best Salon",
"primary_contact": "111111111",
"company_st_address": "Office # 62",
"company_location": "abc",
"company_city": null,
"company_state": null,
"company_country": null,
"company_zip": null,
"company_lat": "27.9506",
"company_long": "82.4572",
"logo_image": "449cbdf0-12ba-11e7-bc65-b7fa1731e4d5.jpeg",
"is_fav_by_client_count": 3,
"client_feedbacks_count": 1,
"user_details": {
"id": 2,
"email": "client@lbb.com"
},
"client_feedbacks": [
{
"id": 1,
"client_id": 1,
"merchant_id": 1,
"stars": 4,
"review_notes": "good client",
"created_at": null,
"updated_at": null
}
]
}
【问题讨论】:
-
已经快3天了还没有答案...
标签: laravel eloquent laravel-5.4 laravel-eloquent laravel-query-builder