问题
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