I have Models Product, ProductVariant, and Department
Department:
id | name | .... Product:
id | name | sku | department_id | .... ProductVariant:
id | product_id | quantity | .... And all associated with each other like:
- Relationship
products: DepartmenthasManyProducts - Relationship
department: ProductbelongsToDepartment - Relationship
variants: ProducthasManyProductVariants - Relationship
product: ProductbelongsToProduct
Everything works as expected between relations over Eloquent calls
Now, using Eloquent I'm trying to retrieve a collection of following columns:
product.id | product.name | product.variant_count | product.stock | department.name By product.stock I mean: $product->variants->sum('quantity'), but I'm having hard time getting SUM inside with() method
What I've tried so far:
$products = Product::select('id', 'name', 'sku', 'department_id') //gives product.name, sku, etc ->withCount('variants') //gives product.variants_count ->with(['variants' => function($query) { $query->select('id', 'product_id', 'quantity'); //gives variants->each.quantity }]) ->with(['department' => function($query) { $query->select('id', 'name'); //gives department.name }]); This code gives something like this:
[ { "id": "2", "name": "Letv LU50609 Earphone - Grey", "sku": "PT-00002", "department_id": "2", "variants_count": "1", "variants": [ { "id": "2", "product_id": "2", "quantity": "35" } ], "department": { "id": "2", "name": "Phones & Tabs Accessories" } }, { "id": "3", "name": "MI In-Ear Headphones Basic 3.5mm HSEJ03JY", "sku": "PT-00003", "department_id": "2", "variants_count": "5", "variants": [ { "id": "3", "product_id": "3", "quantity": "9" }, { "id": "4", "product_id": "3", "quantity": "9" }, { "id": "5", "product_id": "3", "quantity": "10" }, { "id": "6", "product_id": "3", "quantity": "7" }, { "id": "7", "product_id": "3", "quantity": "7" } ], "department": { "id": "2", "name": "Phones & Tabs Accessories" } } ] But what I want to achieve is:
[ { "id": "2", "name": "Letv LU50609 Earphone - Grey", "sku": "PT-00002", "variants_count": "1", "stock": "35", "department": "name": "Phones & Tabs Accessories" }, { "id": "3", "name": "MI In-Ear Headphones Basic 3.5mm HSEJ03JY", "sku": "PT-00003", "variants_count": "5", "stock": "42", "department": "name": "Phones & Tabs Accessories" } ] How can I achieve this???