laravel with查询子表时添加where条件

允许 with 为空:

$this->model->with(['getCollect' => function ($q) use ($user_id) {$q->where('user_id', $user_id);}])

上面的查询方法可以给getCollect关联的表进行条件查询  当不存在时 getCollect 为null

 

实际情况有时候会当getCollect 里条件不成立时整个语句返回空  则按照以下方法利用whereHas就好了:

 

$this->model->whereHas('getCollect' ,function ($quse ($user_id) {$q->where('user_id'$user_id);})->with(['getCollect']);

posted @ 2021-03-01 17:14  をもって剣を制す  阅读(621)  评论(0编辑  收藏  举报