1st table name my_ads
and entries
+----+-------------+--------+----------+---------+
| id | title | gender | country | user_id |
+----+-------------+--------+----------+---------+
| 35 | NOman Javed | male | Pakistan | 1 |
| 34 | Noman Javed | male | Pakistan | 1 |
| 33 | Noman Javed | male | Pakistan | 1 |
| 32 | Noman Javed | male | Pakistan | 1 |
| 31 | Noman Javed | male | Pakistan | 1 |
+----+-------------+--------+----------+---------+
2nd table ads_images
+----+-----------+---------------------------------+
| id | my_ads_id | image_path |
+----+-----------+---------------------------------+
| 28 | 35 | 1645180564-Screenshot-(529).png |
| 27 | 35 | 1645180562-Screenshot-(528).png |
| 26 | 35 | 1645180558-Screenshot-(527).png |
| 25 | 34 | 1645180318-Screenshot-(529).png |
| 24 | 34 | 1645180316-Screenshot-(528).png |
+----+-----------+---------------------------------+
I had written the query and combined it in one array value but I want it to be done with one query.
$all_ads = DB::table('my_ads')->get();
$my_ads_images = DB::table('ads_images')->select('id','my_ads_id', 'image_path')-
>groupBy('my_ads_id')->get();
then compile with both tables values in one array on sub-index
foreach($all_ads as $ads_key => $ads) {
$my_ads_array[$ads_key]['id'] = $ads->id;
$my_ads_array[$ads_key]['title'] = $ads->title;
foreach($my_ads_images as $my_ads_image) {
if($ads->id == $my_ads_image->my_ads_id) {
$my_ads_array[$ads_key]['image_path'] = $my_ads_image->image_path;
}
}
}
Can I write query to achieve $my_ads_array[$ads_key]['image_path'] = array of images here
with one query. I am using Laravel 8 with MySQL.
I know it’s a basic query but I don’t know how it will work. I tried joins but that didn’t work for me don’t know why.
Looking for output like this:
[0] => Array
(
[id] => 35
[title] => Noman Javed
[gender] => male
[description] => Height: 5.6''
[country] => Pakistan
[image_path] => Array
(
[0] => 1645180558-Screenshot-(527).png
[1] => 1645180562-Screenshot-(528).png
[2] => 1645180564-Screenshot-(529).png
)
[created_at] => 2022-02-18 10:35:49
)
Thanks in Advance in case sort this out.