Reputation: 1371
I have two models, User and Event. I made a pivot table, invitations
between User and Event with a status
column. In my Event model definition, I wrote this :
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?
Upvotes: 12
Views: 30936
Reputation: 1
where
should come before with
. This is what eloquent expects.
It should be like this:
$event = Event::with(['owner', 'participants'])->where('id', $id)->first();
Upvotes: -4
Reputation: 163768
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.
Upvotes: 17