【问题标题】:Method addEagerConstraints does not exist方法 addEagerConstraints 不存在
【发布时间】:2018-06-16 05:29:14
【问题描述】:

我有两个模型,用户和事件。我用status 列在用户和事件之间制作了一个数据透视表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.

有人知道为什么吗?

【问题讨论】:

    标签: laravel eloquent lumen


    【解决方案1】:

    where 应该在with 之前。这正是 eloquent 所期望的。

    应该是这样的:

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

    【讨论】:

      【解决方案2】:

      当您尝试这样做时:

      ->with('participants')
      

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

      【讨论】:

      • 所以我尝试了$collection = collect($event); $collection->merge($event->participants);,我得到了App\Event::participants must return a relationship instance
      • @Wizix 再次,您不应该将此方法用作关系。使用方法作为关系时,必须返回belongsTo()hasMany()belongsToMany()等。
      • @Wizix 什么有效?你写的最后一件事是什么??
      猜你喜欢
      • 1970-01-01
      • 2023-03-14
      • 1970-01-01
      • 2018-05-16
      • 2016-11-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多