laravel雄辩的关系,使用“ with”,“ whereHas”和“ whereIn”子句

时间:2018-08-15 09:47:17

标签: laravel octobercms laravel-query-builder

我有一个模型“ Project”,它属于Many sites,每个site属于一个Locality,每个locality属于一个State

另一方面,我有一个用户属于ManyTo States

我想列出与用户状态相同的项目,所以...

$user = Auth::getUser();
$userStates = array();

foreach($user->profile->states as $singleState){
    $userStates[] = $singleState->id;
}

Project::with(['sites','locality','state'])
->whereHas('state', function($q) use($userStates) {
    // Query the name field in status table
    $q->whereIn('id', $userStates); // '=' is optional
})

我正在使用基于laravel构建的OctoberCMS,但是我不断收到错误消息:

Call to undefined method October\Rain\Database\QueryBuilder::state()

1 个答案:

答案 0 :(得分:1)

以下内容将使您的项目仅限于经过身份验证的用户的状态:

$projects = Project::with(['sites.locality.state' => function ($query) {
    $query->whereIn('id', auth()->user()->profile->states->pluck('id')->toArray());
}])->get();

更新

这不应该返回没有站点的项目:

$projects = Project::whereHas('sites.locality.state', function ($query) {
    $query->whereIn('id', auth()->user()->profile->states->pluck('id')->toArray());
}])->get();