我有两个模型,User和Event。我在用户和事件之间创建了一个数据透视表invitations
,其中包含status
列。在我的事件模型定义中,我写了这个:
public function invited()
{
return $this->belongsToMany(User::class, 'invitations', 'event_id', 'user_id')
->withTimestamps()
->withPivot('status')
->orderByDesc('invitations.updated_at');
}
public function participants()
{
$event = $this->with([
'invited' => function ($query) {
$query->where('invitations.status', InvitationStatus::ACCEPTED)->get();
}
])->first();
return $event->invited;
}
但是当我在我的控制器中时:
$event = Event::where('id', $id)->with(['owner', 'participants'])->first();
我有以下错误:
(1/1) BadMethodCallException
Method addEagerConstraints does not exist.
有人知道为什么吗?
答案 0 :(得分:7)
当您尝试这样做时:
->with('participants')
Laravel希望得到一个关系实例。换句话说,您不能将此方法用作关系。
答案 1 :(得分:0)
where
应该在with
之前。这是雄辩的期望。
应该是这样的:
$event = Event::with(['owner', 'participants'])->where('id', $id)->first();