Reputation: 3117
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();
It returns too much information. I want to select something like thí
Is possible with hasOne and belongsTo ?
Upvotes: 1
Views: 1427
Reputation: 12188
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']);
}]);
Upvotes: 2