I used DB::raw()
to achieve this
$album = Albums::select( 'albums.*', DB::raw('(select photo from photos where albums_id = albums.id and status = 1 order by id asc limit 1) as photo') ) ->where('users_id',$user_id) ->where('albums.status',1)->get();
Coding
@JarekTkaczyk was similar and displayed the same result as me, so special thanks to him for his time and efforts ...
But, comparing the runtime for quires
, I stayed on my own like my above snippet
select `albums`.*, (select photo from photos where albums_id = albums.id and status = 1 order by id asc limit 1) as photo from `albums` where `users_id` = '1' and `albums`.`status` = '1'
took 520ฮผs - 580ฮผs
and @JarekTkaczyk
select `albums`.*, `p`.`photo` from `albums` left join `photos` as `p` on `p`.`albums_id` = `albums`.`id` and `p`.`created_at` = (select min(created_at) from photos where albums_id = p.albums_id) and `p`.`status` = '1' where `users_id` = '1' and `albums`.`status` = '1' group by `albums`.`id`
took 640ฮผs - 750ฮผs
but both did the same ...
source share