4

I use laravel 4.2, I'have a table called pois who contain some poi (poi = point of interest), i'have a second table called stamps who contain user stamps.

So i want to have the 3 pois where user have the maximum amount of stamp. My problem is i dont know how to this using laravel queries. I got my result using sql request, but it'snt the good way to do this. here my sql request :

$pois = DB::select("SELECT *, (SELECT count(*) from stamps WHERE pois.id = stamps.poi_id) nbr_stamps FROM pois order by nbr_stamps DESC limit 3"); 

can you tell me how to do this with laravel queries ?

2 Answers 2

3

You should use selectRaw() instead of select() and separate other parts of query to related methods:

$pois = DB::select(DB:raw("*, (SELECT count(*) from stamps WHERE pois.id = stamps.poi_id) nbr_stamps")) ->from('pois') ->orderBy('nbr_stamps', 'DESC') ->limit(3); 

Read the Query Builder documentation.

Sign up to request clarification or add additional context in comments.

10 Comments

Quick reply , Good one !
thanks, but i got the following error : call_user_func_array() expects parameter 1 to be a valid callback, class 'Illuminate\Database\MySqlConnection' does not have a method 'selectRaw'
@Barzull DB should be Illuminate\Support\Facades\DB. Add use DB to the top of the file and try again.
i try with : use Illuminate\Support\Facades\DB as DB at the top of my controller; but nothing change ;(
paste here the result of this: var_dump(get_class(new DB))
|
2

@thanks to limonte for the documentation link, i found the right way to write to select raw, here the solutions :

$pois = DB::table('pois') ->select(DB::raw("*, (SELECT count(*) from stamps WHERE pois.id = stamps.poi_id) nbr_stamps")) ->orderBy('nbr_stamps', 'DESC') ->take(3) ->get(); 

have a nice day ;)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.