例如,我有一张 table ,
id apple orange
1 1 1
2 1 2
3 2 2
我想获取 $apple + $orange > $threshold 的项目。例如,如果 $threshold = 3,则答案将为 No.3。如何在 Laravel 查询生成器中执行此操作?
我尝试了这个问题的filter():How to add two columns value and perform where condition in laravel eloquent
$set = collect($set)->filter(function ($val) use ($threshold) {
return $val->apple + $val->orange > $threshold;
})->values()->all();
它确实有效,但对我来说看起来真的很难看......还有其他方法可以解决这个问题吗?
最佳答案
我将您的要求解释为相当于以下查询:
SELECT *
FROM fruits
WHERE apple + orange > $threshold
如果是这样,那么您可以尝试在以下条件下使用 whereRaw
:
DB::table('fruits')
->whereRaw("apple + orange > ?", array($threshold));
->get();
关于laravel - 如何使用查询生成器根据 Laravel 中两列的总和获取数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46416597/