Let's say I have tables
companies id | name
guests id | name
books id | name
They have models with relations
Company -> hasMany -> Guest
Guest -> hasMany -> Book
Now, I wanna get all books where guests from particular company
I have no Idea how to reach that in eloquent ORM
I will apreciate any help
Thanks
You can use whereHas
to query based on the existence of relationships:
$books = Book::whereHas('guest.company', function ($query) use ($companyId) {
$query->where('id', $companyId);
})->get();
Roughly: get all books that belong to a guest that belongs to a company with id of $companyId
Laravel Docs - 5.6 - Eloquent - Relationships - Querying Relationship Existence
$company = Company::with("guests.books")->find($id);
// or how you get the company doesn't matter
$company->guests->books
// gives you what you're looking for.
Note that, with("guests.books")
is not necessary but, it provides you all data in single query
For more further you may want to check out official docs about relationships