Inventory::select([
'movement_item_type',
'movement_item_id',
'item_id',
'purchase_item_id',
\DB::raw('COALESCE((SELECT SUM(quantity) FROM ecom_inventory ei2 WHERE ei2.purchase_item_id = ei.movement_item_id), 0)) AS `quantity`')
])
->where('ei.movement_item_type', \Ecommerce\PurchaseItem::class)
->groupBy('ei.movement_item_id')
->get();
Help in converting query to eloquent
I need some help in converting this query into eloquent equivalent. The model in which the query is to be executed is named as Inventory. This field should be appended to the column list.
What I am trying to achieve is, say, I already have columns a & b in Inventory and I want to append avl_quantity to it.
Writing Inventory::withAvailableQuantity()->get() should fetch the records from Inventory table with avl_quantity appended to it. I am actually trying to add this extra column via scope to hook on the underlying query builder of the model so that I can run other scopeMethods() on it. e.g,
Inventory::ofItem(2)->withAvailableQuantity()->first()
Here is the full query
SELECT *, (
ei.quantity +
COALESCE((SELECT SUM(quantity) FROM ecom_inventory ei2
WHERE ei2.purchase_item_id = ei.movement_item_id), 0)
) AS `avl_quantity` FROM ecom_inventory ei WHERE ei.movement_item_type = 'Ecommerce\PurchaseItem' GROUP BY ei.movement_item_id
And here is the sub query to fetch only quantity which I want to pass on using $this->addSelect()
(ei.quantity +
COALESCE((SELECT SUM(quantity) FROM ecom_inventory ei2
WHERE ei2.purchase_item_id = ei.movement_item_id), 0)
) AS `avl_quantity`
Here ei is the base table of model.
Please help me in converting this query using query builder.
This is my final solution to it.
public function scopeWithAvailableQuantity($query)
{
return $query->select(
DB::raw($this->getTable() . '.*, (' . $this->getTable() . '.quantity + COALESCE((SELECT SUM(quantity)
FROM ecom_inventory ei2 WHERE ei2.purchase_item_id = ' . $this->getTable() . '.movement_item_id), 0))
AS `avl_quantity`'
)
)->where($this->getTable() . '.movement_item_type', PurchaseItem::class)
->groupBy([$this->getTable() . '.movement_item_id', $this->getTable() . '.item_id']);
}
Please or to participate in this conversation.