Ad

How To Query My Model In Laravel With Relationships Using Query Builder

- 1 answer

I have three models:

  • User
  • Image
  • Post

and their relationship is:

  • User hasMany Image,
  • Image belongsTo User,
  • User hasMany Post,
  • Post belongsTo User,

How can I query out the relationship using query builder until I have the data below?

user_name: name,
image: [
  {
    ... 
  },
  {
   ...
  }
],
post: [
  {
   ...
  },
  {
   ...
  }
]```
Ad

Answer


$user = User::find(1);

$images = $user->images // images is function name as u added in relationship

$posts = $user->posts // posts is function name as u added in relationship


$response = [
'user_name' => $user->name,
'images' => $images,
'posts' => $posts,
];

return response($response);

you can use also

$user = User::with(['images','posts'])->find(1);

Ad
source: stackoverflow.com
Ad