I have a relation of N x 1, Post x User
, have a relationship like the following:
Post.php (model):
....
public function user() {
return $this->belongsTo('User');
}
....
What I want is to select the id
and the username
of the User
model when I access the Post
, but I also want to select only the id
and title
of the Post
model. I want to select all columns).
With this solution :
return Post::with(array('user'=>function($query){
$query->select('id','username');
}))->get();
Return id
and username
of User
of each Post
, then select id
and title
of Post
tried:
return Post::with(array('user'=>function($query){
$query->select('id','username');
}))->select(['id', 'title'])->get();
But unsuccessfully, returning User
to null. I'm using laravel 5.5, if relevant.
Note: I do not want anything 'hard coded' in the models file, because I may want different columns in different situations, preferably liked even if the relation declared in Post.php
would hold.