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

Laravel中如何在whereHas内计算剩余游戏积分并返回数据?

解决方案

实现逻辑说明

  1. 利用whereRaw在whereHas中编写原生SQL表达式,实现字段间的运算过滤(Eloquent查询构造器不直接支持字段比较运算)。
  2. 在关联查询的with闭包里,通过selectRaw计算并返回剩余积分字段,方便后续直接调用。

调整后的代码

$credits = User::select('id', 'username')
    ->where('id', auth()->id())
    // 过滤当前用户在指定阶段下,满足剩余积分条件的game_credits记录
    ->whereHas('game_credits', function($query) use ($phase) {
        $query->where('phase_id', $phase->id)
              // 可根据需求修改条件,例如筛选剩余积分大于0的记录
              ->whereRaw('game_credits - no_of_game_played > 0');
    })
    // 关联查询时计算剩余积分并返回
    ->with(['game_credits' => function($query) use ($phase) {
        $query->select('user_id', 'no_of_game_played', 'game_credits')
              ->where('phase_id', $phase->id)
              // 计算剩余积分并命名为remaining_credits
              ->selectRaw('game_credits - no_of_game_played as remaining_credits');
    }])
    ->first();

调用示例

由于User与game_credits是一对多关联,game_credits返回的是集合对象,可按以下方式访问剩余积分:

// 遍历所有符合条件的游戏积分记录
foreach ($credits->game_credits as $gameCredit) {
    echo "剩余积分:" . $gameCredit->remaining_credits;
}

// 若当前阶段仅存在一条记录,直接取第一个结果
$remainingCredit = $credits->game_credits->first()?->remaining_credits;

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 10:50:22