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;
// return $data;
}
I expect the output object holds list partner offers with AVG all value price for every AdminProduct's
from Newest questions tagged laravel-5 - Stack Overflow http://bit.ly/2Lb4LYu
via IFTTT
Aucun commentaire:
Enregistrer un commentaire