2
考虑下面的模型直接访问关系和在Laravel中使用有何区别?
class User {
public function roles()
{
return $this->hasMany('Roles');
}
}
我可以获取用户详细信息如下
$user1 = User::find(1);
$user2 = User::with('roles')->find(1);
上述两种方法的工作原理相同。即使没有使用with('roles')
,我仍然可以访问该特定用户的roles
。
echo $user1->roles; // Outputs all the roles of that user
所以,我的问题是什么是使用with('relation')
的实际差异/优势?
'用户::与( '角色') - >查找(1);'当您使用'with'它被称为'EAGER LOADING'。而当你使用'$ user1->角色时,'被称为'LAZY LOADING'。参见更多信息https://laravel.com/docs/5.4/eloquent-relationships#constraining-eager-loads和https://laravel.com/docs/5.4/eloquent-relationships#lazy-eager-loading –