You'll have to include the id's in your selects as well otherwise Eloquent won't know what to put where.
Feb 7, 2017
6
Level 2
Eagear Loading Multiple tables
I have following 3 tables with relationship. How can I make eager load these ? Even it is working fine with query builder, I want more perforemance.
Permission
class Permission extends Model
{
public function user_profiles()
{
return $this->belongsTo('App\UserProfile');
}
}
User
class User extends Model
{
public function user_profiles()
{
return $this->belongsTo('App\UserProfile');
}
}
UserProfile
class UserProfile extends Model
{
public function users()
{
return $this->hasMany('App\User');
}
public function permissions()
{
return $this->hasMany('App\Permission');
}
}
How to convert this Query builder to Eager Load
$this->menus = DB::table('users')
->join('user_profiles', 'user_profiles.id', '=', 'users.user_profiles_id')
->join('permissions', 'user_profiles.id', '=', 'permissions.user_profiles_id')
->where('users.id', '=', $this->currentUser)
->select('users.id', 'users.username', 'user_profiles.title', 'permissions.page_name', 'permissions.page', 'permissions.view', 'permissions.submit', 'permissions.print')
->get()->all();
I tried as follows, But it does not work
$this->menus = User::with(['user_profiles' => function ($q) {
$q->select('title');
}, 'user_profiles.permissions' => function ($q) {
$q->select('page_name', 'page', 'view', 'submit', 'print');
}])->where('id', $this->currentUser)->get(['id', 'username'])->all();
Please or to participate in this conversation.