AiD AiD - 4 years ago 134
SQL Question

Laravel 4.2 execute query without using elequent query builder

I have a query with sub-query .. and i want to write an explicite SQL request and execute it
Query :

select count(*) as count from
(
SELECT DISTINCT t.article_id FROM
`articles` as a left join `tags` as t
on a.`id` = t.`article_id`
where a.`flag` = 1
) as sub


i tried this to execute the request without building the query :

DB::connection()->getPdo()->exec( $sql );


But it always return 0 !

Answer Source

You can use sub query with DB::raw. A method DB::raw() (don’t forget to use Illuminate\Support\Facades\DB) allows you to select whatever you want and basically write raw SQL statements.

DB::select(DB::raw("select count(*) as count from 
(
SELECT DISTINCT t.article_id FROM 
`articles` as a left join `tags` as t
on a.`id` = t.`article_id`
where a.`flag` = 1
) as sub"));

https://laravel.com/docs/4.2/queries#raw-expressions

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download