Hula Hula
Hula Hula

Reputation: 573

Select specific columns from both related tables/models

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

Upvotes: 2

Views: 613

Answers (2)

ashok poudel
ashok poudel

Reputation: 723

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 .

Upvotes: 2

Lars Mertens
Lars Mertens

Reputation: 1439

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.

Upvotes: 3

Related Questions