php - Laravel 5: Does Eloquent eager load by default? -


i got structure:

school -> hasmany -> classes

so when tried codes below via artisan tinker

app\school::with('schoolclasses')->find(2283)->schoolclasses; 

i can classes without problem.

but when tried without still same result without problem:

app\school::find(2283)->schoolclasses; 

does eloquent eager loads default? if so, how disable it?

no, laravel not eager load default. lets take step step. lets ignore ->schoolclasses; moment.

app\school::with('schoolclasses')->find(2283); 

this query database twice. first, school primary key of 2283. then, query database , related schoolclasses.

app\school::find(2283); 

this query database once. school. there no eager loading done far. if debug , keep track of database queries, see query database once while eager loading query twice.

when try access schoolclasses doing ->schoolclasses;, works. why same results? bit deceptive, it's not same. when try access schoolclasses, laravel check if has been eager loaded. if so, return collection of schoolclasses. no querying done. returns them. however, if did not eager load them, laravel query database on spot , schoolclasses. ultimately, particular example, same results, when query database different.

however, poor example of main benefit eager loading.

the main benefit of eager loading alleviate n + 1 query problem. lets want 5 schools , of classes. without eager loading, do:

$schools = school::take(5)->get();  foreach ($schools $school) {     $schoolclasses = $school->schoolclasses; } 

that total of 6 queries such simple task. added comments below understand queries coming from:

$schools = school::take(5)->get(); // first query  foreach ($schools $school) {     // each school, querying database again related classes.     // 5 schools = 5 more queries     $schoolclasses = $school->schoolclasses; } 

however, if eager load everything, have 2 queries:

// 2 queries here fetches $schools = school::with('schoolclasses')->take(5)->get();  foreach ($schools $school) {     // no more queries done classes because     // have been eager loaded     $schoolclasses = $school->schoolclasses; } 

Comments

Popular posts from this blog

how to insert data php javascript mysql with multiple array session 2 -

multithreading - Exception in Application constructor -

windows - CertCreateCertificateContext returns CRYPT_E_ASN1_BADTAG / 8009310b -