Cannot run raw Query in Laravel 4

守給你的承諾、 提交于 2019-12-10 21:34:56

问题


I need to get total count to show in my page.

I can run this & loop through & get the total number

DB::table('table1')
    ->select((DB::raw('MAX(score)')))
    ->where('status', 1)
    ->groupBy('user_id')
    ->get();

But this query would give me the count in just a single query & I don't need run any extra loop to get the total.

SELECT COUNT( * ) FROM (
  SELECT MAX( score ) FROM table1
  WHERE status =1
  GROUP BY user_id
) AS totalCounter

How am I suppose to run this RAW query in Laravel 4?


回答1:


As mentioned by other contributors;-

DB::select('SQL QUERY GOES HERE WITH PARAMETERS ?, ?', array('parameter 1', 'parameter 2'));

The code above should permit raw sql.

However,

DB::table('table1')
    ->select((DB::raw('MAX(score)')))
    ->where('status','=', 1)
    ->groupBy('user_id')
    ->count();

Should achieve the same effect for the task you seek it for, and is more in tune with laravels philosophy.




回答2:


Try

DB::statement( 'Your Query' );

or

DB::select( 'Your Query' );



回答3:


DB::select(DB::raw("SQL QUERY CODE HERE"))

Both raw and select are require!

Please see for more info: Laravel 4: how to run a raw SQL?




回答4:


Try this

DB::select( DB::raw("SELECT * FROM table_Name WHERE col = :somevariable"), array(
   'somevariable' => $someVariable,
 ));


来源:https://stackoverflow.com/questions/16601409/cannot-run-raw-query-in-laravel-4

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