0
votes

I have three models

Posts
Users
UserImages

In Posts I have

public function user() {
    return $this->belongsTo(new User)->with('avatar');
}

In User I have

public function avatar() {
    return $this->hasOne(UserImage::class)->where('type', 1); //type 1 is avatar;
}

I call from Posts controller and I have screenshot below:

$posts = $this->model::select('*')->with('user')->get();

enter image description here

It returns too much information. I want to select something like thí

enter image description here

Is possible with hasOne and belongsTo ?

1

1 Answers

2
votes

you can join the eager loading query to get the desired result:

$posts = $this->model::select('*')->with(['user'=>function($query) {
            $query->join('avatars', 'avatars.user_id', 'users.id')
                ->select(['users.id', 'users.name', 'users.userName', 'avatars.images_url']);
        }])->get();

to use 'avatar' relation you can use multi eager loading:

 $posts = $this->model::select('*')->with(['user'=>function($query) {
                $query->select(['users.id', 'users.name', 'users.userName'])
                ->with(['avatar'=>function($query){
                    $query->select(['user_id','images_url']);
                }]);