Laravel 计算相关列的 AVERAGE

标签 laravel laravel-5.4 eloquent laravel-query-builder

我正在尝试计算相关专栏的平均评分。 Merchant 和 ClientFeedbackReviews 模型之间存在关系(1->许多)。

商家模型

[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');
}
:::::::::::::::::::::::::::::::::::::

我需要获得所有商家的平均评分(作为我计算结果的查询的一部分 - 根据附近距离、给定位置或根据请求数据使用搜索字符串的商家)

我几乎尝试了在互联网上找到的所有内容,但无法在结果中获得“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": "<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="1c7f70757972685c70756e327f7371" rel="noreferrer noopener nofollow">[email protected]</a>"
},
"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": "<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="71121d18141f05311d13135f121e1c" rel="noreferrer noopener nofollow">[email protected]</a>"
},
"client_feedbacks": [
  {
    "id": 1,
    "client_id": 1,
    "merchant_id": 1,
    "stars": 4,
    "review_notes": "good client",
    "created_at": null,
    "updated_at": null
  }
]

}

最佳答案

好的。所以这完成了下面的工作blog :

    public function avgFeedback() {

    return $this->hasMany('App\ClientFeedbackReviews', 'merchant_id', 'id')
                    ->selectRaw('merchant_id,AVG(client_feedback_merchants.stars) AS average_rating')
                    ->groupBy('merchant_id');
}

public function getavgFeedbackAttribute() {
    // if relation is not loaded already, let's do it first
    if ($this->relationLoaded('commentsCount'))
        $this->load('avgFeedback');

    $related = $this->getRelation('avgFeedback');

    // then return the count directly
    return ($related) ? (int) $related->average_rating : 0;
}

我使用它的方式如下:

    //////// query continued /////////

    $getMerchantQuery = $getMerchantQuery->with('avgFeedback');

    ///////  query continued //////////

关于Laravel 计算相关列的 AVERAGE,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43413093/

相关文章:

php - 在 apache2 执行 60 秒后网关超时

Laravel hasOne Relation 2 列

php - 获取除 first() 以外的特定行

php - Laravel Collective Form 复选框总是被选中

php - RouteCollection.php 第 251 行中的 MethodNotAllowedHttpException

php - laravel Eloquent 一对多关系返回null

php - Laravel 5 - 重定向到 HTTPS

laravel - 在 WITH 子句中使用 SELECT 急切加载关系返回空

mysql - 使用 Laravel 选择倒数第二条记录 - Eloquent

php - 优化页面充电时间(使用 Eloquent 请求)