I can't figure out how to eager load a sum of a relationships columns.
Database (simplified) is as follows;
TABLES
PRODUCT PRODUCT_VARIATIONS
*ID* *ID*
*NAME* *NAME*
*AVAILABLE_STOCK*
I have my relationships set up as follows;
public function variations()
{
return $this->hasMany('Product_variation');
}
When loading all Products I want to be able to see the SUM of all stock for that product attached to the product object itself.
A product may have many variations.
I can return the entire INDIVIDUAL variations attached to the products (See Below)
$products = Product::with('variations')->paginate(15);
but I just want to return all the products with a simple integer showing their available_stock count taking into account all variations.
I want to be able to type
@foreach ($products as $product)
$product->available_stock // Returns INT
@endforeach