Laravel DB query SUM of two column equals to another table column and count them
I got four tables products, productions, workables and embroidery stock logs.
So each production has many morph to product table saved on workables with pivot issued_quantity column. Embroidery stock logs has production_id, product_id, received_embroidery and received_damage. When production is created product_id, workable_id(which is production id) and issued_quantity is inserted on workables table. If i receive a certain product on production suppose 5 as received embroidery then it will enter 5 as received_embroidery and 0 as received_damage , thus we can enter until it reaches the issued_quantity. Basically i want to get all productions with products count and how many products has reached it's issued_quantity.
I got upto products count . But how many achived sum of those two columns value to issued_quantity i can't get it.
here is one code through which i can get both but i want it in SQL query not to run on each rows.
$model = Production::select(['productions.*']);
$model->leftJoin('workables',function($join){
$join->on('workables.workable_id','=','productions.id')->where('workables.workable_type','=','App\Models\Production');
})
->selectRaw('count(workables.product_id) as products_count');
return datatables()
->eloquent($model)
->addColumn('totally_received_products_count',function(Production $production){
$count = array();
foreach($production->products as $i =>$product){
$issued = $product->pivot->issued_quantity;
$get = EmbroideryStockLog::where([['production_id',$production->id],['product_id',$product->id]])->sum(DB::raw('received_embroidery + received_damage'));
if($issued == $get){
$count[]=$get;
}
}
return count($count);
})->filterColumn('products_count', function($query, $keyword) {
$query->whereExists(function ($query) use ($keyword) {
$query->from('workables')->havingRaw('count(workables.product_id) like ?',["%{$keyword}%"]);
});
})->toJson();
anyone can help on this?
Please or to participate in this conversation.