Laravel Where和OrWhere多个条件 [英] Laravel Where and OrWhere multiple conditions
本文介绍了Laravel Where和OrWhere多个条件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下查询:
$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();
我的问题是此查询返回所有用户的项目,而不是给定的 user_Id.
.这是因为orWhere适用于所有 wheres
,但是我需要它仅适用于此:
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")
如何修复查询以仅返回给定的$ this-> id个用户项目?
How I can fix the query to return only the given $this->id user items?
推荐答案
Laravel支持高级where子句
如下:
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();
与使用 orWhere
相比,我认为另一种选择(更清洁,更易于阅读IMO)可能是使用
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();
这篇关于Laravel Where和OrWhere多个条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文