laravel中的子查询 - with()

时间:2016-07-19 00:32:52

标签: php laravel laravel-5.1

我使用以下行进行查询:

$items = $this->model->with('subCategory')->get();

但是我想在with()方法中添加一个查询,因为我只想从with()获取状态等于0的项目。

我怎样才能做到这一点?

2 个答案:

答案 0 :(得分:2)

L5文档中有“急切加载”。 Here

$items = $this->model->with(['subCategory' => function ($query) {
  $query->where('status', 0); }])->get();

答案 1 :(得分:1)

这些被称为eagarload约束,你可以使用闭包来实现你的结果

例如

$items = $this->model->with(['subCategory'=>function($q){
    $q->whereId('5');
    //or any other valid query builder method.
}])->get();

让我知道你是怎么过的。

相关问题