prgrm
prgrm

Reputation: 3833

Adding a number from a database to an existing variable to perform a query

I am not sure if this is possible to do without doing a query first.

I have something like this:

$item_weight

This item goes into a box, which has its own row $box->weight and has a max weight $box->max_weight.

I want a list of boxes that I could put my item into.

I know I can do this by doing a query first and then calculating with a foreach but I wonder if there is a cleaner way to do this.

Something like this:

$boxes= Boxes::where('max_weight','>',$item_weight + $box->weight)
                ->orderBy('max_weight','asc')
                ->get();

Upvotes: 0

Views: 38

Answers (1)

Alex Blex
Alex Blex

Reputation: 37048

You can use whereRaw and shift calculation to db side:

$boxes= Boxes::whereRaw('boxes.max_weight - boxes.weight > ?', [$item_weight])
    ->orderBy('max_weight','asc')
    ->get();

Upvotes: 2

Related Questions