I have a table "vehicles" that has a column "wheels", which is an integer count of the number of wheels.
I also have a table "wheels", which is in a "belongsTo/hasMany" relationship with Vehicles (note the count in the vehicles may not match the number of records in the wheels table - e.g. we might know a vehicle takes 6 wheels, but only have specific info (and therefore records for) 2 of those wheels).
The problem I am having is when using Vehicles::with('wheels')
The wheels collection is overwriting the count.
I can get both the collection and the count by aliasing the count select->('wheels as wheels_count','vehicles.*')->with('wheels')
but, if I then try to use the collection
$vehicles->each(function($vehicle, $k){
$vehicle->wheels->each(function($wheel, $kk){
$wheel->makeHidden('vehicle_id');
});
});
I get an error: Call to a member function each() on int
because laravel still thinks the wheels property on each vehicle is an int, not a collection.
Unfortunately, aliasing the "with" isn't an option. I could loop through the vehicles and obtain the wheels, but then I'm loosing the benefit of eager loading.
Any thoughts on my best approach?
you can use the getRelation()
method
$vehicle->wheels // 2 (your count)
$vehicle->getRelation('wheels') // your relation