You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何对Illuminate\Database\Eloquent\Collection每条投注记录执行利润计算

解决方案

针对Laravel Eloquent集合的批量计算需求,有两种常用实现方案:

方法1:临时遍历计算(仅单次使用)

如果你只需要本次计算用到profit属性,直接调用集合的each方法遍历赋值即可:

// $bets 为你拿到的投注集合实例
$bets->each(function ($bet) {
    // 注意将字符串格式的odds转为数值类型,避免计算异常
    $bet->profit = (float)$bet->odds * $bet->unit_id;
});

操作完成后,你可以直接通过$bet->profit获取对应记录的计算结果。

方法2:定义模型访问器(全局通用)

如果profit属性是高频使用字段,推荐直接在Bet模型中定义访问器,后续所有查询到的Bet实例(包括集合内的条目)都可以直接调用该属性,无需重复计算:

  1. 打开app/Models/Bet.php文件,添加对应访问器:
use Illuminate\Database\Eloquent\Casts\Attribute;

class Bet extends Model
{
    // 模型原有其他代码...

    // Laravel 9及以上版本写法
    protected function profit(): Attribute
    {
        return Attribute::make(
            get: fn () => (float)$this->odds * $this->unit_id,
        );
    }

    // Laravel 8及更早版本写法
    // public function getProfitAttribute()
    // {
    //     return (float)$this->odds * $this->unit_id;
    // }

    // 若需要在模型序列化输出(如接口返回、toArray())中自动带上profit字段,添加以下配置
    protected $appends = ['profit'];
}
  1. 定义完成后,任意场景下都可以直接调用属性取值:
// 单条记录取值
$profit = Bet::find(1)->profit;

// 集合内批量取值
$bets = Bet::all();
foreach ($bets as $bet) {
    echo $bet->profit;
}

补充说明:如果要计算扣除本金后的净盈利,只需要把公式改为 (float)$this->odds * $this->unit_id - $this->unit_id 即可。

内容的提问来源于stack exchange,提问作者Jetz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.23 18:06:00