yifei3212
yifei3212

Reputation: 851

How to use query builder to get data depending on the sum of two column in Laravel?

For example, I have a table,

id   apple   orange
 1       1        1
 2       1        2
 3       2        2

and I want to get the item where $apple + $orange > $threshold. For example, if $threshold = 3, then the answer will be No.3. How can I do this in the Laravel query builder?

I tried the filter() from this question: 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();

It does work but looks really ugly to me... Are there any other ways to solve this?

Upvotes: 2

Views: 128

Answers (1)

Tim Biegeleisen
Tim Biegeleisen

Reputation: 521073

I interpret your requirement as being equivalent to the following query:

SELECT *
FROM fruits
WHERE apple + orange > $threshold

If so, then you can try using whereRaw with this condition:

DB::table('fruits')
    ->whereRaw("apple + orange > ?", array($threshold));
    ->get();

Upvotes: 3

Related Questions