【问题标题】:(laravel eloquent) get nearest values (tipping game)(laravel eloquent) 获得最接近的值 (打赏游戏)
【发布时间】:2017-02-02 19:47:14
【问题描述】:

我创建了一个小费游戏,用户可以猜测一个值,12 小时后,API 请求将采用当前的美元/欧元汇率,并且小费最接近值的获胜者将获胜(只有一个获胜者,如果 n 用户小费相同数量的所有人都将获胜)。

如何从数据库中获取“最近”的提示?

            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 orm eloquent laravel-5.2 nearest-neighbor


    【解决方案1】:

    我不熟悉您框架中的语法,但这里有一种可以重构的 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 之外编写上述逻辑。

    主要是您需要确定最接近金额的小费,并将其用作选择/过滤获胜者的参数。

    【讨论】:

      猜你喜欢
      • 2011-04-13
      • 1970-01-01
      • 1970-01-01
      • 2022-01-13
      • 2016-08-05
      • 2019-04-02
      • 1970-01-01
      • 1970-01-01
      • 2020-03-20
      相关资源
      最近更新 更多