gpt4 book ai didi

php - 根据用户排名而不是分数进行排名

转载 作者:行者123 更新时间:2023-11-29 10:38:41 24 4
gpt4 key购买 nike

我有一个无法解决的问题。

我正在使用 Laravel 框架。

我正在尝试根据排名制作一个排名表(这意味着用户没有任何分数,他们只有排名)

我希望它的工作方式如下:

用户 A = 展示位置:1

用户 B = 展示位置:10

用户 B 战胜了用户 A,然后用户 B 被列为第一名用户 A 被放置为编号 2,然后我希望它相应地更新所有其他用户。

我似乎找不到可靠的方法来做到这一点。

最佳答案

我认为这不是 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();
}

更新逻辑正如 Classified 所指出的,它移动了行,但没有正确执行,因此我正在更新逻辑以使其按预期工作,并且它也会更简单一些。

$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();
}

关于php - 根据用户排名而不是分数进行排名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45944585/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com