I have some problem, I don't understand how to count AVG value when get all value from model. I have 2 model's. First it's AdminProduct - hold base info about product. Second model it's - PartnerOffer - hold partners offers for AdminProduct. And i have pivot table partner_offer_admin_product - hold 2 foreign keys for table & field 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);
}

Migration 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;
}

I expect the output object holds list partner offers with AVG all value price for every AdminProduct's

1 Answers

0
Rifqi On

You can do it programmatically leveraging Collections from eloquent (not using separate queries), like following:

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;
      });
  }

I haven't tested the code yet, but it should work. Goodluck.