public function events () {
return $this->belongsToMany(Event::class)->orderBy('date', 'desc');
}
public function next_event() {
return $this->events()->first();
}
Order by pivot table field
Hi there! Couldn't find an answer for this one, even after longer searching: I want to order a list of items by the date of an "event" (event like "birthday", "wedding" and so on, not like an event in a programming language). An item can have multiple events, but I want the items to be ordered by the event that happens next. Simplified, I would really like to do in my ItemsController something like:
$items = Item::with('nearest_event')->orderBy('nearest_event')->get();
So I tried to add this to my Item model:
public function nearest_event()
{
return $this->belongsToMany('App\Event')->orderBy('date')->first();
}
It seems that it isn't possible like this, I get this error: "Call to undefined method Illuminate\Database\Query\Builder::addEagerConstraints()" Is there a way to get only the first result from a many-to-many-relation? Maybe my thinking how to do this is totally wrong and someone can help me cut the knot in my head ^^ Thanks in advance! Jonas
Please or to participate in this conversation.