Laravel 5: Eloquent – querying relationship

Eloquent: querying relationship

All types of Eloquent relationships also serve as query builders, allowing you to continue to chain constraints onto the relationship query before finally executing the SQL against your database.
They are lazy loaded. They can be eager loaded to avoid n+1.

Getting data
Use dynamic property

Run get() on method

Chain builder methods

querying relationship existence
get only sellers that sell any ebooks

get only sellers that sell more than 2 ebooks (constraint)

get only posts that have comments with some votes on them

get  all posts with at least one comment containing words like foo%

There is also ‘orWhereHas‘ property available.

get seller that does not sell any ebooks

get ebooks which are not written by author with name starting at ‘Isaac’

count ebook titles (models) sold by given seller

count many models with constraints

eager loading

To check how many queries your code produces, use this.

Lazy loading – this code will produce multiple queries

Eager loading – this code will produce only 2 queries

Eager loading on multiple relations

Nested eager loading (dot notation)
Here we get authors with their ebooks.

Eager loading with constraints

All builder methods are available here.

Lazy eager loading

Turn lazy load code into eager, if some condition is met.

Additional constraints:

Inserting & Updating Related Models
Save

Save many

Create

Belongs To Relationships:
associate

This method will set the foreign key on the child model.

dissociate

This method will set the relationship’s foreign key to null.


More – see Laravel docs.