sharonnsp's avatar

Laravel Eloquent: hasMany

I am doing a warehouse system project and i need to built a pie chart to calculate the warehouse_location and then at another StockBalance table i need to calculate how many location are occupied, anyone can guide me ? thanks

0 likes
2 replies
LaryAI's avatar
LaryAI
AI
Best Answer
Level 58

To calculate the warehouse location and the number of occupied locations, you can use Laravel's Eloquent relationships. Assuming you have a Warehouse model and a StockBalance model, you can define a hasMany relationship between them.

In your Warehouse model, define the relationship like this:

public function stockBalances()
{
    return $this->hasMany(StockBalance::class);
}

Then, you can use the withCount method to get the count of related StockBalance records for each Warehouse:

$warehouses = Warehouse::withCount('stockBalances')->get();

This will give you a collection of Warehouse models, each with a stock_balances_count attribute that contains the count of related StockBalance records.

To calculate the number of occupied locations, you can sum the quantity column of the related StockBalance records:

$occupiedLocations = Warehouse::with('stockBalances')->get()->sum(function ($warehouse) {
    return $warehouse->stockBalances->sum('quantity');
});

This will give you the total quantity of all StockBalance records across all Warehouse locations.

You can then use this data to build your pie chart.

sharonnsp's avatar

@LaryAI I am getting an error "Unsupported operand types: int + Domain\Shared\Foundation\ValueObjects\Quantity" can i know why will get this error ?

Please or to participate in this conversation.