0

I would like to reproduce following mySQL query using Laravel query builder:

*SELECT SUM(scores) FROM (SELECT scores FROM player_games WHERE player_id = 1 ORDER BY id DESC LIMIT 2) scores

Any suggestions?

Here the solution:

    $sub = playerGame::where('player_id',1)->where('scores','>',0)->limit(2)->orderBy('id','desc');

    $count = DB::table( DB::raw("({$sub->toSql()}) as sub") )
   ->mergeBindings($sub->getQuery()) 
   ->sum('scores');
   return $count;
5
  • $responce= DB::table('player_games')->sum('amount')->where('player_id ', 1)->order_by('id','desc')->limit(2)->first(); i think some thing like this. Commented Oct 11, 2018 at 6:30
  • Hi, it does not work. I also tried yesterda. Commented Oct 11, 2018 at 6:37
  • please show the error and your code..... Commented Oct 11, 2018 at 6:50
  • This is the query: $res = DB::table('player_games')->sum('scores')->where('player_id',1)->limit(3)->first(); Commented Oct 11, 2018 at 7:11
  • Error: Call to a member function where() on string" Commented Oct 11, 2018 at 7:12

2 Answers 2

1

Use fromSub():

$sub = playerGame::select('scores')
    ->where('player_id', 1)
    ->where('scores', '>', 0)
    ->limit(2)
    ->orderBy('id','desc');
$sum = DB::query()->fromSub($sub, 'scores')->sum('scores');
Sign up to request clarification or add additional context in comments.

Comments

0
$responce= DB::table('player_games')->where('player_id',1)->sum('amount');
        dd(collect($responce)->sortByDesc('id')->take(2)); 

please cheack this one.....i try it's work....and add use DB;in the top of controller....

3 Comments

It returns 120...all the scores...not limit 2
Please see this if still facing any problem then ping me. stackoverflow.com/questions/24823915/…
Hi, thanks for sharing the link...now it works...I posted the solution above.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.