I don't remember exactly, but i was working on my laravel 5+ application 2 months ago. At that moment i require to write subquery in select statement. I simply write in my mysql query and check it's work perfect. But i though how can it possible to write using laravel query builder.
So first i am going to explain what was that. I have two tables "posts"
posts
id, name, detail, created_at, updated_at
post_viewer
id, post_id, user_id
So, i written following mysql query you can simply read.
Mysql Query:
SELECT
posts.*,
(SELECT count(*) FROM post_viewer
WHERE post_viewer.post_id = posts.id
) as total_viewer
FROM `posts`
I think now you can understand, what was the issue. So finally i found solution using DB::raw(). So let's see bellow laravel convert query.
Laravel Query Builder:
$data = \DB::table("posts")
->select("posts.*",
\DB::raw("(SELECT count(*) FROM post_viewer
WHERE post_viewer.post_id = posts.id
) as total_viewer"))
->get();
I hope you found your best solution....
Do you like below Tutorials ?
- Laravel - chmod(storage/oauth-private.key): Operation failed: Operation not permitted
- Laravel 7.x and 6.x datatables example from scratch
- How to compress PNG image using pngquant in PHP?
- Laravel 7.x and 6.x Chart example using Charts Package
- Guzzle http client GET and POST request example in Laravel 5
- Laravel schema default current timestamp value example
- Laravel 7.x and 6.x Get Site URL Examples
- Convert object to array in laravel 7.x and 6.x example