AiD
AiD

Reputation: 1007

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 !

Upvotes: 0

Views: 2483

Answers (3)

shafiq.rst
shafiq.rst

Reputation: 1296

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

Upvotes: 2

Saravanan Sampathkumar
Saravanan Sampathkumar

Reputation: 3261

Using DB::select should solve your problem.

DB::select('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');

Upvotes: 0

Aleksander Koko
Aleksander Koko

Reputation: 111

Why don't you try with DB::raw('your sql query here')

Upvotes: 0

Related Questions