我有一個問題,我無法包裹我的頭。根據用戶排名而不是得分排名
我正在使用Laravel框架。
我試圖讓基於位置排序表(即用戶沒有任何得分,他們只是有個展示位置)
我它是如何想的工作方式如下:
用戶A =放置:1個
用戶B =放置:10
用戶B戰勝用戶A,然後用戶B被放置爲數1和用戶A被放置爲數2,然後我希望它相應地更新所有其他用戶。
我似乎無法找到一個可靠的方法來做到這一點。
我有一個問題,我無法包裹我的頭。根據用戶排名而不是得分排名
我正在使用Laravel框架。
我試圖讓基於位置排序表(即用戶沒有任何得分,他們只是有個展示位置)
我它是如何想的工作方式如下:
用戶A =放置:1個
用戶B =放置:10
用戶B戰勝用戶A,然後用戶B被放置爲數1和用戶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();
}
修訂LOGIC 作爲分類中指出,它繞着行,但不這樣做是正確,所以我更新邏輯使其按照預期工作,而且會稍微簡單一些。
$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();
}
我會明確地嘗試這個明天,並看看它是如何發展的。一旦我嘗試並測試它,我會發表評論。 – Classified
這解決了潛在的問題。然而,如果只有三個用戶,這不能正確工作,那麼如果第二名用戶移動到第一名,那麼第三名將是第五名。 – Classified
你是對的!我假設所有記錄都必須更新,但是實際上,需要更新的記錄是位置交換之間的記錄。我用新提出的邏輯更新了我的答案,讓我知道這是否適合您! – Lvkz
你的意思是所有的Laravel的魔術它不會爲你做?我只是徘徊在周圍。你只需要對數據庫行進行更新。也許而不是放置你可以做比例。這會容易很多。 –
@BrianGottier我不確定我是否遵循,我不知道你用百分比來表示你的意思。放置基本上是用戶的等級。如果我要更新贏家和輸家的排名,那麼會出現重複(兩位用戶排名相同) - 我怎麼能避免這種情況? – Classified
其實,看看這個:https://stackoverflow.com/questions/5207267/update-increment-a-single-column-on-multiple-rows-at-once,並想象在那裏的where子句。你也可以在查詢中減去。不應該很難弄清楚。 –