Ad
How To Query My Model In Laravel With Relationships Using Query Builder
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
Related Questions
- → I can't do a foreign key, constraint error
- → How to implement DbDongle::convertTimestamps as workaround of invalid timestamps with MySql strict
- → MySQL error "Foreign key constraint is incorrectly formed"
- → Eloquent Multitable query
- → "Laravel 5.1" add user and project with userId
- → Database backup with custom code in laravel 5 and get the data upto 10 rows from per table in database
- → Laravel 5.1 QueryException when trying to delete a project
- → Using Array in '->where()' for Laravel Query Building
- → Chaining "Count of Columns" of a Method to Single Query Builder
- → Laravel Eloquent Joining Strange query
- → convert time using mysql laravel 5
- → How to update a column after an expiration date in MySQL?
- → Foreign key constraint fails on existing key
Ad