I have a relationship N x 1, Post x User
, the Post->User have a relation like the following:
Post.php (model):
....
public function user() {
return $this->belongsTo('User');
}
....
I want to select just the id
and username
from User model when I extract each Post, but I also want just the id
and title
from the Post (not every column from the Post model).
return Post::with(array('user'=>function($query){
$query->select('id','username');
}))->get();
I can get the id
and username
from the User
, but I'm also extracting all columns from the Post
model, not what I want, so o tried:
return Post::with(array('user'=>function($query){
$query->select('id','username');
}))->select(['id', 'title'])->get();
Although unsuccessfully, the User
became null, and I was left with id
and title
from the Post.
I'm returning json response, in case that's relevant.
Note: I don't want anything 'hard coded' on my Post.php model file, because I may want for the same relation different columns for different situations, so I would like to keep the relation has it is on Post.php