lundi 16 janvier 2017

Laravel: Nesting query join results in a sub array

NOTE Please do not suggest using Eloquent, this is specifically for the Laravel query builder.

For performance reasons we are using Query Builder to retrieve results from a table:

DB::table('posts')->get();

If we then want to join a relation onto that query:

DB:table('posts')
    ->leftJoin('comments', 'posts.id', '=', 'comments.post_id')
    ->get();

The results are merged into the array of each post:

[
    'id'                => 1,
    'title'             => 'My Blog Post',
    'content'           => '<h1>This is a post</h1><p>hello world</p>',
    'post_author'       => 'Billy',
    'comment'           => 'This is a comment',
    'comment_author'    => 'Andrew',
]

How can we have the joined results placed into a nested array? Such as:

[
    'id'                => 1,
    'title'             => 'My Blog Post',
    'content'           => '<h1>This is a post</h1><p>hello world</p>',
    'post_author'       => 'Billy',
    'comment'           => [
        'id'                => 22,
        'comment'           => 'This is a comment',
        'comment_author'    => 'Andrew',            
    ],
]



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2ixrDh7
via IFTTT

Aucun commentaire:

Enregistrer un commentaire