3

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?

Laurence
  • 58,936
  • 21
  • 171
  • 212
Tanvir Gaus
  • 205
  • 1
  • 3
  • 10

4 Answers4

9

Try

DB::statement( 'Your Query' );

or

DB::select( 'Your Query' );
Safeer
  • 714
  • 4
  • 3
6

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.

Daniel Luca CleanUnicorn
  • 1,087
  • 1
  • 12
  • 30
Shayne
  • 1,571
  • 1
  • 16
  • 20
2
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?

Community
  • 1
  • 1
tfont
  • 10,891
  • 7
  • 56
  • 52
0

Try this

DB::select( DB::raw("SELECT * FROM table_Name WHERE col = :somevariable"), array(
   'somevariable' => $someVariable,
 ));
TZHX
  • 5,291
  • 15
  • 47
  • 56
Manish
  • 328
  • 3
  • 9