I am trying to pull all records that have an event relationship which has an event date of today. I have the following code:
EventStaffStation::with([
'event' => function($query) {
$query->where('event_date', Carbon::now()->format('d-m-Y'));
}
])->where([
'staff_id' => auth()->user()->id
])->has('event')->get()
This gives me a record event_staff_stations but it sets the event relationship to null. I want the record to not be returned if the relationship is null.
Basically if event_staff_station record isn't for today then I don't want it returned. I'm only interested in records with an event day of today.
Any help is appreciated.
You should use:
EventStaffStation::whereHas(
'event' , function($query) {
$query->where('event_date', Carbon::now()->format('d-m-Y'));
}
)->where([
'staff_id' => auth()->user()->id
])->get()
If you want to get records based on relationship existence/condition you should use has/whereHas
instead of with
. Of course in above query you can also add with
that will eager load any relationship you want if needed.
You should use both whereHas
and with
.
whereHas
will check the existence of the relation and with
will return record with relationship object.
EventStaffStation::whereHas(
'event' , function($query) {
$query->where('event_date', Carbon::now()->format('d-m-Y'));
}
)->with('event')
->where([
'staff_id' => auth()->user()->id
])->get();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.