2

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).

With this solution:

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

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Hula Hula
  • 553
  • 8
  • 20
  • Try this `Post::with(array('user'=>function($query){ $query->select('id','username'); }))->get(['id', 'title']);` – Maraboc Oct 31 '17 at 22:38
  • @Maraboc, done it the result is the `User` null, I'm not using blade, this is for a json response (if that's relevant) – Hula Hula Oct 31 '17 at 22:41

2 Answers2

3
Post::select('id', 'title', 'user_id')
->with(array('user'=>function($query){
    $query->select('id','username');
}))->get();

You need the foreign key to maintain the relationship between the two models.

Lars Mertens
  • 1,389
  • 2
  • 15
  • 37
2

This is usually how I do it.

Post::select('id','title','user_id')->with('user:id,username')->get();

For this, you need to define the relationship properly and you must select the foreign key form the post table .

aircraft
  • 25,146
  • 28
  • 91
  • 166
ashok poudel
  • 703
  • 11
  • 28