我想使用Laravel查询构建器重现以下mySQL查询:
*SELECT SUM(scores) FROM (SELECT scores FROM player_games WHERE player_id = 1 ORDER BY id DESC LIMIT 2) scores
有什么建议吗?
解决方法:
$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;
答案 0 :(得分:0)
$responce= DB::table('player_games')->where('player_id',1)->sum('amount');
dd(collect($responce)->sortByDesc('id')->take(2));
请仔细检查一下这个.....我尝试它的工作....并在控制器顶部添加use DB; ...
答案 1 :(得分:0)
使用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');