Laravel 4.2 execute query without using elequent query builder

荒凉一梦 提交于 2019-12-25 16:47:45

问题


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 !


回答1:


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




回答2:


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');



回答3:


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



来源:https://stackoverflow.com/questions/41983462/laravel-4-2-execute-query-without-using-elequent-query-builder

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!