方法addEagerConstraints不存在

时间:2018-01-06 17:25:04

标签: laravel eloquent lumen

我有两个模型,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.

有人知道为什么吗?

2 个答案:

答案 0 :(得分:7)

当您尝试这样做时:

->with('participants')

Laravel希望得到一个关系实例。换句话说,您不能将此方法用作关系。

答案 1 :(得分:0)

where应该在with之前。这是雄辩的期望。

应该是这样的:

$event = Event::with(['owner', 'participants'])->where('id', $id)->first();
相关问题