(laravel eloquent) 获取最接近的值(小费游戏)
(laravel eloquent) get nearest values (tipping game)
我创建了一个小费游戏,用户可以猜测一个值,12 小时后,USD/EUR 请求将采用当前的 USD/EUR 费率,给出最接近小费的获胜者将获胜(仅一个赢家,如果 n 个用户给了相同的小费,他们都会赢)。
如何从数据库中获取 "nearest" 小费?
foreach ($rounds_closed as $round_closed)
{
//get latest rate
$amount = 458.12;
//set transaction as processed and set latest rate
$round_closed->update([
'status' => 2,
'win_tip' => $amount,
]);
//get lucky winners
//here I would need eloquent code to choose the "nearest" winners
$winners_transactions = Transaction::where('round_id', $round_closed->id)->where('assessment', $round_closed->win_tip)->get();
//if we have at least one winner
if ($winners_transactions->count() > 0)
{
//calculate their win amount
$sum = $round_closed->transactions->sum('amount');
$fee = $sum * 0.10;
$sum = $sum - $fee;
$sum = number_format($sum / $winners_transactions->count(), 8, '.', '');
foreach ($winners_transactions as $winner_transaction)
{
//mark transaction as payed out
$winner_transaction->update([
'payout' => 1,
]);
//payout user
}
}
}
我不熟悉你框架中的语法,但是 SQL 中有一个你可以重构的可能方法:
SET @amount = 458.12;
#Order tips by smallest difference and return the first result
SET @winning_tip = (SELECT tip FROM tips ORDER BY ABS(tip-@amount) ASC LIMIT 1);
#Return all users with the winning tip value
SELECT userid, tip, ABS(tip-@amount) AS delta FROM tips WHERE tip = @winning_tip
http://sqlfiddle.com/#!9/fac65/2
根据您的数据大小,您还可以撤回所有事务并在 SQL.
之外编写上述逻辑
主要是您需要确定哪个小费最接近金额,并将其用作 select/filter 获胜者的参数。
我创建了一个小费游戏,用户可以猜测一个值,12 小时后,USD/EUR 请求将采用当前的 USD/EUR 费率,给出最接近小费的获胜者将获胜(仅一个赢家,如果 n 个用户给了相同的小费,他们都会赢)。
如何从数据库中获取 "nearest" 小费?
foreach ($rounds_closed as $round_closed)
{
//get latest rate
$amount = 458.12;
//set transaction as processed and set latest rate
$round_closed->update([
'status' => 2,
'win_tip' => $amount,
]);
//get lucky winners
//here I would need eloquent code to choose the "nearest" winners
$winners_transactions = Transaction::where('round_id', $round_closed->id)->where('assessment', $round_closed->win_tip)->get();
//if we have at least one winner
if ($winners_transactions->count() > 0)
{
//calculate their win amount
$sum = $round_closed->transactions->sum('amount');
$fee = $sum * 0.10;
$sum = $sum - $fee;
$sum = number_format($sum / $winners_transactions->count(), 8, '.', '');
foreach ($winners_transactions as $winner_transaction)
{
//mark transaction as payed out
$winner_transaction->update([
'payout' => 1,
]);
//payout user
}
}
}
我不熟悉你框架中的语法,但是 SQL 中有一个你可以重构的可能方法:
SET @amount = 458.12;
#Order tips by smallest difference and return the first result
SET @winning_tip = (SELECT tip FROM tips ORDER BY ABS(tip-@amount) ASC LIMIT 1);
#Return all users with the winning tip value
SELECT userid, tip, ABS(tip-@amount) AS delta FROM tips WHERE tip = @winning_tip
http://sqlfiddle.com/#!9/fac65/2
根据您的数据大小,您还可以撤回所有事务并在 SQL.
之外编写上述逻辑主要是您需要确定哪个小费最接近金额,并将其用作 select/filter 获胜者的参数。