我正在研究根据各种标准过滤用户的功能。其中一个过滤器基于用户净值。在数据库中,我们目前仅存储净资产和净债务,计算净资产只是从资产中减去债务。
我的过滤功能需要能够在目标号,目标号或两个目标号之间找到用户。
在eloquent的代码中,这就是我所拥有的。
//more code before...
// filter net worth
->when(isset($request_filter_params['minNetWorth'])
|| isset($request_filter_params['maxNetWorth']), fn ($query) =>
$query->whereHas('net_worth_estimate_calc_response', fn ($q) =>
$q->select(DB::raw('(net_worth_estimate_asset - net_worth_estimate_debt) as net_worth'))
->when(isset($request_filter_params['minNetWorth']), fn ($qq) =>
$qq->where('net_worth', '>=', $request_filter_params['minNetWorth'])
)
->when(isset($request_filter_params['maxNetWorth']), fn ($qqq) =>
$qqq->where('net_worth', '<=', $request_filter_params['maxNetWorth'])
)
)
)
//more code after...
它产生的SQL:
select
*
from
`users`
where
and `is_active` = 1
and `is_groupadmin` = 0
and exists (
select
(net_worth_estimate_asset - net_worth_estimate_debt) as net_worth
from
`user_net_worth_estimate_calculator_responses`
where
`users`.`id` = `user_net_worth_estimate_calculator_responses`.`user_id`
and `net_worth` >= 2500
and `net_worth` <= 10000)
order by
`updated_at` desc
该SQL产生错误Unknown column 'net_worth' in 'where clause'
。
显然是由我的自定义DB::raw('(net_worth_estimate_asset - net_worth_estimate_debt) as net_worth')
调用引起的,是否有任何方法可以根据该派生值在该条款中进行过滤?还是MySQL无法做到的事情,我必须将其移至PHP层(我很想避免)?
编辑:“ user_net_worth_estimate_calculator_responses”只有user_id (bigint)
,net_worth_estimate_asset (double)
,net_worth_estimate_debt (double
,A PK id
和几个时间戳。模型文件是完全标准的eloquent模型。
分析解答
您可以尝试:
$qq->having('net_worth', '>=', $request_filter_params['minNetWorth'])
或者与Wheraw一起使用(这应该具有更好的性能)
$qq->whereRaw('net_worth_estimate_asset - net_worth_estimate_debt >= ?', $request_filter_params['minNetWorth'])