我有以下查询:
$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适用于所有where's
,但我需要它仅适用于此:
->where('items.type',"stones")
->orWhere('items.type',"fish")
如何修复查询以仅返回给定的$ this-> id用户项?
答案 0 :(得分:2)
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();
答案 1 :(得分:0)
使用闭包,如下所示:
$userId = $this->id;
$items = UserItems::join('items','items.id','=','user_items.item_id')
->where('user_id','=', $userId)
->where('quantity','>',0)
->where(function($query) {
$query
->where('items.type',"stones")
->orWhere('items.type',"fish");
})
->get();