laravel eloquent 关系使用 "with"、"whereHas" 和 "whereIn" 子句

laravel eloquent relationship using "with", "whereHas" and "whereIn" clauses

我有一个模型 "Project" 属于多个 sites 并且每个 site 属于一个 Locality 并且每个 locality 属于一个 State.

另一方面,我有一个用户属于 ToMany 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()

以下应该让您获得仅限于经过身份验证的用户状态的项目:

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

更新

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

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