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 –