Upskilling Is The Key To Moving Forward
September 21, 2020Get Started With Bitbucket Pipelines: A simple PHP Composer Pipeline
October 16, 2020Eloquent is amazing, and 90% of queries can be dealt with using where, find, has, etc. But sometimes we need to query a relationship itself. E.g.
Let's say we have the following Models: Car, Garage, Owner.
An Owner can have many Garages, but a Garage can only have one Owner.
A Garage can have many Cars, but a Car can only belong to one Garage.
Since a car belongs to a garage, and a garage belongs to an owner, we can query a cars owner using Eloquents'
hasOneThrough
method.
But since an owner can have many garages, how can we easily get all of their cars? This is where the power of whereHas
comes in.
This will return all cars that belong to a garage owned by the owner that $owner_id matches with.