Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel: how to eager load a model that's two steps down?

Tags:

php

laravel

Let's say I have users which have many computers which belong to a certain computer_type (users->computers->computer_type).

I know that I can load both users and their computers with: User::with("Computer")

I would like to load all three. How can I do it in Laravel?

like image 679
duality_ Avatar asked Dec 07 '12 14:12

duality_


People also ask

How eager loading works in laravel?

Eager loading is super simple using Laravel and basically prevents you from encountering the N+1 problem with your data. This problem is caused by making N+1 queries to the database, where N is the number of items being fetched from the database.

How does eager loading work?

Eager loading is the process whereby a query for one type of entity also loads related entities as part of the query. Eager loading is achieved by the use of the Include method. It means that requesting related data be returned along with query results from the database.

What is eager loading and lazy loading laravel?

} Dynamic properties are "lazy loading", meaning they will only load their relationship data when you actually access them. Because of this, developers often use eager loading to pre-load relationships they know will be accessed after loading the model.


2 Answers

To retrieve relationships that far down, you must say the child, then the child with it's child, and so on...

User::with(array('computer', 'computer.type'))->find(1);

User has_one Computer has_one type in this particular scenario.

like image 102
Joel Larson Avatar answered Sep 19 '22 07:09

Joel Larson


Try

Appointment::with('kid.parent')->get()

if each kid has a appointment and each kid has a parent.

like image 29
windmaomao Avatar answered Sep 18 '22 07:09

windmaomao