Reputation: 29
I am beginner Laravel developer. I use in my project Laravel 8.
I have migration:
Schema::create('selected_product_ingredients', function (Blueprint $table) {
$table->id();
$table->bigInteger('product_id')->unsigned()->default(0);
$table->foreign('product_id')->references('id')->on('products')->onDelete('cascade');
$table->bigInteger('ingredient_id')->unsigned()->default(0);
$table->bigInteger('group_id')->unsigned()->default(0);
$table->bigInteger('single_product_analysis_id')->unsigned()->default(0);
$table->boolean('type')->default(false);
$table->decimal('weight', 12, 3)->nullable()->default(0);
$table->foreign('ingredient_id')->references('id')->on('laboratoryingredients')->onDelete('cascade');
$table->timestamps();
});
and controller:
$itemsAll = $this->selectedProductIngredient->with(['item'])
->select('product_id', 'ingredient_id')
->selectRaw('sum(weight) as weight_sum')
->where('single_product_analysis_id', 0)
->where('group_id', $id)
->where('type', 2)
->groupBy('ingredient_id')
->orderByDesc('weight_sum')
->get();
dd($itemsAll)
Illuminate\Database\Eloquent\Collection {#1969 ▼
#items: array:6 [▼
0 => App\Models\SelectedProductIngredient {#1975 ▼
#fillable: array:6 [▶]
#guarded: array:1 [▶]
#dates: array:2 [▶]
#casts: array:2 [▶]
#connection: "mysql"
#table: "selected_product_ingredients"
#primaryKey: "id"
#keyType: "int"
+incrementing: true
#with: []
#withCount: []
#perPage: 15
+exists: true
+wasRecentlyCreated: false
#attributes: array:3 [▼
"product_id" => 18
"ingredient_id" => 4
"weight_sum" => "224.000"
]
It's work fine.
I need to make one change. In the weight_sum field, I need to divide the weight_sum by the number of summarized records (weight_sum / quantity).
So we currently have:
weight_sum = 6
I would like to get w weight_sum = 6: 3 (3 records) = 2
How can I do this?
Please help
Upvotes: 1
Views: 218
Reputation: 5735
I'd go with an accessor:
class ProductIngredient extends Model
{
public function getAverageWeight()
{
return $this->item->avg('weight');
// same as: $this->item->sum('weight') / $this->item->count();
}
}
Or you can add another relation aggregation function to the query:
$itemsAll = $this->selectedProductIngredient->with(['item'])->withAvg('item', 'weight')
->select('product_id', 'ingredient_id')
->selectRaw('sum(weight) as weight_sum')
->where('single_product_analysis_id', 0)
->where('group_id', $id)
->where('type', 2)
->groupBy('ingredient_id')
->orderByDesc('weight_sum')
->get();
Upvotes: 1