如何通过枢轴字段获取AVG值

时间:2019-04-29 07:39:21

标签: laravel laravel-5 eloquent eloquent--relationship

我有一些问题,当我从模型中获取所有值时,我不明白如何计算AVG值。 我有2个模特。首先是AdminProduct-保存有关产品的基本信息。 第二个模型是PartnerOffer-保留合作伙伴提供的AdminProduct。 我有数据透视表partner_offer_admin_product-拥有2个表和字段price的外键。

AdminProduct.php

public function partnerOffers()
{
    return $this->belongsToMany(PartnerOffer::class, 'partner_offer_admin_product')->withPivot('price);
}

PartnerOffer.php

public function adminProducts()
{
    return $this->belongsToMany(AdminProduct::class, 'partner_offer_admin_product')->withPivot('price);
}

迁移partner_offer_admin_product.php

Schema::create('partner_offer_admin_product', function (Blueprint $table) {
    $table->unsignedBigInteger('admin_product_id');
    $table->unsignedBigInteger('partner_offer_id');

    $table->unsignedDecimal('price', 10, 2);

    $table->foreign('admin_product_id')->references('id')->on('admin_products')->onDelete('cascade');
    $table->foreign('partner_offer_id')->references('id')->on('partner_offers')->onDelete('cascade');
});

AdminProductRepository.php

public function getAll()
{
    $products = AdminProduct::all();
    // How to count avg value via pivot table field `price`
}

    // How count Avg by id AdminProduct best. Below my solution.
public function getOffers($id)
{
    $avg = DB::select('select avg(`price`) as value from `partner_offer_admin_product` where `admin_product_id` =' . $id);
    // dd ($avg);

    $collection = collect([
        'item' => [
            'product'   => AdminProduct::with('partnerOffers')->find($id),
            'avg_price' => $avg,
        ],
    ]);

    return $collection;
}

我希望输出对象包含AVG的列表合作伙伴提供的所有AdminProduct的所有价格

1 个答案:

答案 0 :(得分:0)

您可以以编程方式利用雄辩的Collections(不使用单独的查询),如下所示:

public function getAll()
  {
      $products = AdminProduct::with('partnerOffers')->get();

      // Below adds a custom field to each row with averaged value of field `price` from the pivot table
      return $products->map(function ($product) {
          $product['avg_price'] = $product->partnerOffers->avg('price');
          return $item;
      });
  }

我还没有测试代码,但是应该可以。祝你好运。