3
I have an N x 1 relationship, 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 model User when I access the Post, but I also want to select only the id and title of the model Post (do not want to select all columns).
With this solution:
return Post::with(array('user'=>function($query){
$query->select('id','username');
}))->get();
Yes returns the id and username of User of each Post, to then select the id and the title of Post tried:
return Post::with(array('user'=>function($query){
$query->select('id','username');
}))->select(['id', 'title'])->get();
But without success, returning the User a null. I am using Laravel 5.5 if relevant.
Note: I don’t want anything 'hard coded' in the models file, because I may want different columns in different locations, preferably I would really like the ratio declared in Post.php remained.
I did a test with a similar situation and your code is correct. What error, is returning
null?– Andre Gusmao
'Error', is when I try to select also only a few columns columns of the post @Andréluizdegusmão . In my second scenario the
idand thetitlereturn correctly but the user is null– Hula Hula
You can post both
Modelsand the two tables?– novic
@Virgilionovic, there’s not much more in my models. This is for a json answer (if relevant), I’m not using Lade.
– Hula Hula
@Hulahula I know the problem I’m going through in an answer is already ready
– novic