0

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');
}
Community
  • 1
  • 1
Greendrake
  • 3,657
  • 2
  • 18
  • 24

1 Answers1

1

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

cresjie
  • 469
  • 2
  • 13
  • Wow, that's it, thank you! However, the foreign key is already defined in the `Post` model's `thread` method. Is there any way to get Laravel to add it to the `select` call automatically in order to avoid specifying the foreign key twice? – Greendrake Mar 11 '16 at 00:11