方法 addEagerConstraints 不存在
Method addEagerConstraints does not exist
我有两个模型,用户和事件。我用 status
列在用户和事件之间创建了一个枢轴 table、invitations
。在我的事件模型定义中,我这样写:
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.
有人知道为什么吗?
当您尝试这样做时:
->with('participants')
Laravel 期望得到一个关系实例。换句话说,您不能将此方法用作关系。
where
应该在 with
之前。这就是 eloquent 所期望的。
应该是这样的:
$event = Event::with(['owner', 'participants'])->where('id', $id)->first();
我有两个模型,用户和事件。我用 status
列在用户和事件之间创建了一个枢轴 table、invitations
。在我的事件模型定义中,我这样写:
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.
有人知道为什么吗?
当您尝试这样做时:
->with('participants')
Laravel 期望得到一个关系实例。换句话说,您不能将此方法用作关系。
where
应该在 with
之前。这就是 eloquent 所期望的。
应该是这样的:
$event = Event::with(['owner', 'participants'])->where('id', $id)->first();