Laravel“where”查询关系表

时间:2016-05-20 20:22:58

标签: laravel

这是我的疑问:

@ManyToOne (fetch = FetchType.LAZY)
@JoinColumn (name = "user_id")
private User         user;

我需要$items = UserItems::with('item') ->where('user_id','=',$this->id) ->where('quantity','>',0) ->where('items.type','=',"shirt") ->get(); type的所有项目。

查询返回:

shirt

由于某些原因,Column not found: 1054 Unknown column 'items.type' in 'where clause'在此查询中未被识别为表格,我无法使用`在其中的位置。

然后我如何获取项目类型为items的所有用户项目?

2 个答案:

答案 0 :(得分:1)

Decision

尝试:

$items = UserItems::with(['item' => function($query){
    return $query->where("type", "shirt")
})
->where('user_id','=',$this->id)
->where('quantity','>',0)
->get();

答案 1 :(得分:1)

您实际上需要使用whereHas来处理此问题......

$items = UserItems::with('item')
        ->whereHas('item', function($q) {
            $q->where('type', 'shirt');
         })
        ->where('user_id','=',$this->id)
        ->where('quantity','>',0)
        ->get();
相关问题