I have the following query:
$items = UserItems::join('items','items.id','=','user_items.item_id')
->where('user_id','=',$this->id)
->where('quantity','>',0)
->where('items.type',"stones")
->orWhere('items.type',"fish")
->get();
My problem is that this query returns the items of ALL users instead of the given user_Id.
. It's because the orWhere applies on all of the where's
but I need it to apply only on this:
->where('items.type',"stones")
->orWhere('items.type',"fish")
How I can fix the query to return only the given $this->id user items?
Laravel supports Advanced Where Clauses
like such:
$items = UserItems::join('items','items.id','=','user_items.item_id')
->where('user_id','=',$this->id)
->where('quantity','>',0)
->where(function($query) {
$query->where('items.type',"stones")
->orWhere('items.type',"fish");
})
->get();
I guess another option (cleaner, easier to read IMO), as opposed to using orWhere
, could be to use the whereIn
operator like:
$items = UserItems::join('items','items.id','=','user_items.item_id')
->where('user_id','=',$this->id)
->where('quantity','>',0)
->whereIn('items.type', ["stones", "fish"])
->get();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With