简体   繁体   中英

Laravel Eloquent nulls in whereHas

I'm trying to display all business locations hours for the current day and if the location does not have hours listed in the database, I'm wanting to show it but as null.

Example:

Business 1: 10:00 am - 5:00 pm
Business 2: 10:00 am - 9:00 pm
Business 3: Closed (null)
Business 4: 10:00 am - 5:00 pm

The issue i'm having is in the controller. It's not showing the nulls with the whereHas clause.

$Locations = Locations::with('StoreHours', 'Managers', 'ShiftLeads')
                ->doesntHave('StoreHours')->orWhereHas('StoreHours', function ($query) {
                    $query->where('opening_time','>=', date('Y-m-d') . ' 00:00:00');
                    $query->where('opening_time','<=', date('Y-m-d') . ' 23:59:59');
                })
            ->get();

The only data that is showing is if any store has never had store hours. How can I show all stores and get null if there is no hours?

The issue with your query is that locations that have store hours for any day other than today will not be selected.

It seems to me that you want all locations, regardless of whether they have store hours or not. Just remove the restrictions on the store hours relationship from the query. That will give you all your locations, and then your view can determine if there are store hours to display for today.

Edit

From your comment, I assume what you really want to do is to restrict the store hours that are eager loaded to only those hours for today, so that you're not loading a bunch of store hours you don't care about. You can do that by tweaking the parameters passed to your with() method. Your code would look something like:

$locations = Locations::with([
        'Managers',
        'ShiftLeads',
        'StoreHours' => function ($query) {
            return $query
                ->where('opening_time', '>=', date('Y-m-d') . ' 00:00:00')
                ->where('opening_time', '<=', date('Y-m-d') . ' 23:59:59');
        }
    ])
    ->get();

Now, only those store hours that match the closure will be eager loaded onto each location. You can read more about constraining eager loading in the documentation here.

Another option would be to create a second relationship that only loads the store hours for today, and eager load that relationship instead of the full store hours relationship. If you're only doing this in one place, the extra work may not be worth it, but you may want to consider this if you need this logic all over the place.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM