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

Laravel Eloquent查询中如何无需新增字段通过计算筛选商品

Eloquent查询净价低于指定值的实现方法

你可以直接在SQL查询层面做字段运算,无需新增表字段,以下是几种常用实现方案:

方案1:直接使用whereRaw(最简实现)

通过whereRaw方法写入净价计算逻辑,同时使用参数绑定避免SQL注入风险:

Product::whereRaw('gross_price - discount_amount < ?', [100])->get();

如果gross_price或discount_amount字段允许为空,可以用COALESCE函数处理null值,避免计算结果异常:

Product::whereRaw('COALESCE(gross_price, 0) - COALESCE(discount_amount, 0) < ?', [100])->get();

方案2:封装查询作用域(复用性更高)

如果项目中频繁用到净价查询条件,可以在Product模型中封装查询作用域:

// 在Product模型中添加作用域方法
public function scopeWhereNetPriceLessThan($query, $targetValue)
{
    return $query->whereRaw('gross_price - discount_amount < ?', [$targetValue]);
}

后续调用时直接使用封装好的方法即可,代码更简洁易读:

Product::whereNetPriceLessThan(100)->get();

方案3:同时返回净价字段

如果需要在查询结果中同步返回计算好的净价值,可以通过DB::raw定义别名:

use Illuminate\Support\Facades\DB;

Product::select('*', DB::raw('gross_price - discount_amount as net_price'))
    ->whereRaw('net_price < ?', [100])
    ->get();

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 12:39:03