hasMany relation using withTrashed(), add a 'only before' date
Laravel's soft deletes are useful. But I have a case that I am sure must be common. I need to display a trashed relationship, but only if the relation was deleted before a specific date, based on the parent.
My case is Events, and Seat Types. Events have many Seat Types. (eg 1 theatre event has standard seats, VIP seats, house seats)
When an event date is before the deleted_at date of a seattype, I want to relate the seat type to the event. When the deleted_at date of the seat types was after the event date, I don't want to pull the relation.
Any pointers on this would be great - perhaps this is not possible with Eloquent, since the where clause of the deleted_at will need to be different for each of the rows of the event table.
// Event.php
public function seats()
{
return $this->hasMany(Seat::class)
->withTrashed()
->where(function ($query) {
$query->whereNull('deleted_at') // it has not been deleted
->orWhere('deleted_at', '>', $this->date); // it was deleted after Event date
});
}
Do you mean $this->date is not accessible in the function? Try this:
// Event.php
public function seats()
{
return $this->hasMany(Seat::class)
->withTrashed()
->where(function ($query) use ($this) {
$query->whereNull('deleted_at') // it has not been deleted
->orWhere('deleted_at', '>', $this->date); // it was deleted after Event date
});
}