我有一个模型“ 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()
答案 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();