我有一个问题,我无法解决这个问题。
我正在使用Laravel框架。
我正在尝试根据展示位置制作排名表(意味着用户没有任何分数,他们只是有展示位置)
我希望它如何工作是以下方式:
用户A =展示位置:1
用户B =展示位置:10
用户B 胜过用户A ,然后用户B 获得数字1 和用户A 被设置为数字2 ,然后我希望它相应地更新所有其他用户。
我似乎无法找到一种可行的方法。
答案 0 :(得分:1)
我认为这不是一个Laravel挑战,而是一个SQL挑战。解决起来可能很简单:基本上,你会询问失败者的实际位置,如果位置大于胜利者,你什么都不做,否则你会将失败者的位置分配给新的胜利者并更新表格的其余部分在位置栏中有+1。
在代码中它会是这样的:
$winner_player = User::where('id', userA->id)->first();
$loser_player = User::where('id', userB->id)->first();
if($winner_player->position < $loser_player->position) {
//Update the rest of the users.
//We add 2 because we need space for the new winner and for
//the loser that is still above of the rest of the players.
DB::table('users')
->where('position', '>', $loser_player->position)
->update(DB::raw('position+2'));
//Set the winner with the actual position of the loser.
$winner_player->position = $loser_player->position;
$winner_player->save();
//Set the looser with the new position (+1 of his actual).
$loser_player->position = $loser_player->position + 1;
$loser_player->save();
}
更新逻辑 正如分类指出的那样,它会移动行但不能正确执行,因此我正在更新逻辑以使其按预期工作,并且它也会更简单一些。
$winner_player = User::where('id', userA->id)->first();
$loser_player = User::where('id', userB->id)->first();
if($winner_player->position < $loser_player->position) {
//Set the winner with the actual position of the loser.
$winner_player->position = $loser_player->position;
//Update the users between the swap. There is no need to update
//the whole table, we only update the records between the swap.
DB::table('users')
->where([['position', '<', $winner_player->position],
['position', '>=', $loser_player->position]])
->update(DB::raw('position+1'));
//Save the value of the winner AFTER updating the positions
//between winner and loser.
$winner_player->save();
}