Getting data from two table with one query
I have two tables posts
and images
and I want to get all the posts and related images with below code:
$posts = Post::leftJoin('images','posts.postId','images.postId')
->where('countryId', $id)
->groupBy('posts.postId')
->orderby('posts.postId', 'desc')
->select('posts.*','images.*', 'posts.postId as postId')
->get();
But the problem is that I get only one image of the post instead of all images because one post have multiple images.
Current Json response is:
[
{
"postId": 103,
"text": 'This is the post text',
"countryId": 75,
"imageId": 152,
"imageLink": "C9hGzwVKlOrL.jpg",
"imageDescription": ""
},
...
]
And I want to change it like this:
[
{
"postId": 103,
"text": 'This is the post text',
"countryId": 75,
"images" : [
{
"imageId": 152,
"imageLink": "C9hGzwVKlOrL.jpg",
"imageDescription": "This is the 1st image description"
},
{
"imageId": 153,
"imageLink": "JHKJdiuIuoi.jpg",
"imageDescription": "This is the 2nd image description"
},
...
]
},
...
]
You shouldn't try to get hierarchical/nested data using one query. Eloquent has "Relationships" functionality for that: https://laravel.com/docs/8.x/eloquent-relationships#one-to-many
In your case you need to add "images" relation to Post
model:
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
public function images()
{
return $this->hasMany(Image::class, 'postId', 'postId');
}
}
Then:
$posts = Post::where('countryId', $id)
->orderBy('postId', 'desc')
->select('posts.*','images.*', 'posts.postId as postId')
->get();
foreach ($posts as $post) {
$post->images; // = collection of all images related to this post
}