Eloquent query to 'merge' / 'join' / 'union' 2 related tables

Posted 3 years ago by domioanna

Let's say I had 2 tables, linked by a one-to-many relationship.

  • Post - belongsTo a user
  • User - hasMany posts

I know I could set up the relationships and call a post with it's owner like so...

$post = Post::with('owner')->first();

...but this returns a collection of the post with the user nested inside of it, like this:-

[
    'id' => 1,
    'user_id' => 1,
    'title' => "Some title...",
    'body' => "Some body...",
    'owner' => [
        'id' => 1,
        'username' => "johndoe",
        'email" => "john@example.com"
    ]
]

Is there a way to effectively 'join' or 'merge' those 2 sets of data into one record, so it would look like this...

[
    'id' => 1,
    'title' => "Some title...",
    'body' => "Some body...",
    'username' => "johndoe",
    'email" => "john@example.com"
]

I know there'd be conflicting fields like id, created_at, etc, I would only look to pull across certain fields.

I know this concept is a bit of a backwards way of doing it for this scenario, but for the actual scenario I need it for it will save me a lot of trouble.

Thanks in advance

Please sign in or create an account to participate in this conversation.

Reply to

Use Markdown with GitHub-flavored code blocks.