如何用不同的值(从1到3)更新前三个结果:
查询以获取前3个结果:
$top3 = DB::table('quests')
->orderby('score', 'desc')
->take(3)
->pluck('id');
查询以更新排名为1到3的列:
DB::table('quests')->whereIn('id', $top3)
->first()->update(['rank', 1])
->second()->update(['rank', 2])
->third()->update(['rank', 3]);
//of course the above updates are from my imagination :)
//just trying to describe what I'm trying to do
您的第二个查询是多余的;没有理由要查询ids
只是再次查询表。在一个查询/循环中完成所有操作:
$top3 = Quest::orderBy("score", "DESC")->take(3)->get();
foreach($top3 AS $index => $quest){
$quest->rank = $index+1;
$quest->save();
}
注意:这里假设您有Quest
模型;仍然可以使用DB::table()
,但是如果您使用的是Laravel,请使用模型。
上面的代码将在单个查询中提取3条记录,正确处理排序和限制,然后循环并分配一个等级(基于0 $index
,在每个循环中递增,对处理加1)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句