jeudi 10 mars 2016

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?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire