Greendrake
Greendrake

Reputation: 3734

Get specific fields from both parent and child models

I am trying to retrieve a model instance along with its related one so that only certain fields are retrieved from both. This and this questions answer how to do that for related models and it works well for me:

$hash = \Post::whereId(1075)
                        ->with(['thread' => function($query) {
                            $query->select('id', 'title');
                        }])
                        ->first()
                        ->toArray();
print_r($hash);
Array
(
    [id] => 1075
    [title] => Blablablablam,
    [text] => Blablablablablablabl,
    [created_at] => 2015-10-17 13:00:00
    [updated_at] => 2015-10-17 13:00:00
    [thread] => Array
        (
            [id] => 180
            [title] => Blablablablam
        )
)

However, if I try to limit the fields for the Post model as well, then the Thread data is not retrieved at all:

$hash = \Post::whereId(1075)
                        ->with(['thread' => function($query) {
                            $query->select('id', 'title');
                        }])
                        ->addSelect('title')
                        ->first()
                        ->toArray();
print_r($hash);
Array
(
    [title] => Blablablablam,
    [thread] => 
)

So, how to retrieve only certain fields from both the main and related models?

UPDATE

Here is what worked for me after I saw the cresjie's answer:

$hash = \Post::whereId(1075)
                        ->with(['thread' => function($query) {
                            $query->select('id', 'title');
                        }])
                        ->addSelect('title', 'thread_id')
                        ->first()
                        ->toArray();
print_r($hash);
Array
(
    [title] => Blablablablam,
    [thread_id] => 180,
    [thread] => Array
        (
            [id] => 180
            [title] => Blablablablam
        )
)

The only thing that still puzzles me is that the foreign key (thread_id) needs to be specified explicitly even though is it already specified in the Post class:

public function thread()
{
    return $this->belongsTo(Thread::class, 'thread_id');
}

Upvotes: 0

Views: 409

Answers (1)

cresjie
cresjie

Reputation: 469

the Thread data was not retrieved because you need also to select the foreign keys in your Post

Upvotes: 1

Related Questions