php - What is the difference in accessing relation directly and using with in Laravel? -
consider following model
class user { public function roles() { return $this->hasmany('roles'); } }
i can fetch user details below
$user1 = user::find(1); $user2 = user::with('roles')->find(1);
both above methods works same. without using with('roles')
, can still access roles
of particular user.
echo $user1->roles; // outputs roles of user
so, question actual difference/advantage using with('relation')
?
the with()
function used eager loading. when loading 1 user have little impact. when try roles
property, query roles user executed, user.
now consider loading list of users database. when call roles
property each of these users, query executed every user. not way work.
when use with()
function, relations eager loaded. wich means laravel load roles
in 1 query , assign them correct user objects. when call roles
property on user objects now, values loaded no database query needed. reducing amount of queries 2.
Comments
Post a Comment