Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

lara96's avatar

Get data from 3 tables with relationship and select columns

I have 3 tables

users -id -email -password and other columns...

user_details -id -user_id[FK_users] -first_name -last_name

posts -id -user_id[FK_users]

Now i already created all the relationships in the models and now i can access the user_details table by below eloquent query it returns whole users table and user_details table but i only want to select first_name and last_name from user_details table how do i do that?

$posts= Post::with('city:id,name_en', 'user.userDetail')->where('id', $id)->get();

0 likes
5 replies
lara96's avatar

Post Model

public function user(){
    return $this->belongsTo(User::class);
}

public function city(){
    return $this->belongsTo(City::class);
}

User Model

public function userDetail(){
    return $this->hasOne(UserDetail::class);
}

public function post(){
    return $this->hasOne(Post::class);
}

UserDetail Model

public function user(){
    return $this->belongsTo(User::class);
}

public function city(){
    return $this->belongsTo(City::class);
}
lara96's avatar

@Artak So is this method also eager loading?

lara96's avatar
lara96
OP
Best Answer
Level 1

I found answer myself

Returns whole user table and slected columns from third relationship table (user_details)

$posts = Post::with(['city:id,name_en', 'user.userDetail' => function($query)
    {
        $query->select('first_name', 'last_name', 'user_id');
    }])->where('id', $id)->first();

Below eloquent query returns the users table id and user_details table user_id, first_name and last_name

$posts= Post::with(['city:id,name_en',
    'user' => function ($query) {
         $query->select('id');
    },
   'user.userDetail' => function($query) {
        $query->select(['user_id', 'first_name', 'last_name']);
    }
])->where('id', $id)->get();

Please or to participate in this conversation.