laravel 方法 addEagerConstraints 不存在

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/48129911/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 17:12:59  来源:igfitidea点击:

Method addEagerConstraints does not exist

laraveleloquentlumen

提问by Louis Etienne

I have two models, User and Event. I made a pivot table, invitationsbetween User and Event with a statuscolumn. In my Event model definition, I wrote this :

我有两个模型,用户和事件。我制作了一个数据透视表,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;
}

But when in my controller I do :

但是在我的控制器中时,我会这样做:

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

I have the following error :

我有以下错误:

(1/1) BadMethodCallException
Method addEagerConstraints does not exist.

Does someone know why?

有人知道为什么吗?

回答by Alexey Mezenin

When you're trying to do this:

当您尝试执行此操作时:

->with('participants')

Laravel expects to get a relationship instance. In other words, you can't use this method as a relation.

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

回答by Ahmad

whereshould come before with. This is what eloquent expects.

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

It should be like this:

应该是这样的:

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