Sérgio Reis
Sérgio Reis

Reputation: 2523

Laravel select object as property

I'd like to know if it is possible to do a left join in a query and if it exists instead of having all the columns in the same "level" make the joined table go as a property (This without any relationships)

For example

$users = user::leftJoin("posts","users.id","=","posts.user_id")->get();

Instead of returning every field together,

["id"/*This actually gets messed up if select doesn't choose which to use*/,
  "name",
  "age",
  /*Now post fields*/
  "tile",
  "date_posted"
  ...
]

and having it return

["id",
  "name",
  "age",
  "post"=>[
    "id",
    "tile",
    "date_posted"
    ...
   ]
]

Edit: If possible to avoid loops for obvious reasons... I know it is possible and in last resort will use them but not using loops would help out a lot

Upvotes: 1

Views: 1180

Answers (1)

Sandeesh
Sandeesh

Reputation: 11916

You're using eloquent for the users table. Why not use relationships? It does exactly what you want. Create a new Post model. Then add the following relationship to your User model.

public function posts()
{
    return $this->hasMany(Post::class);
}

You can now fetch the users with post like so

$users = User::with('posts')->get();

The result is exactly what you want. Also I've used User in my example, where as you've used user. The result would contain the posts object as posts instead of post as you've shown in the example, you can change this property name by changing the relationship method name. I've used these since they're the right convention.

Upvotes: 2

Related Questions