Search code examples
phplaravel-5eloquenteloquent-relationship

Eloquent Relationship Count Constraint


I am trying to write an eloquent query that would work as follows:

Tables:
Order
Support Ticket (one to many with the order)

Query: Filter the support tickets and only show the order if the support ticket is less than 45 days old.

I feel like this would be an adaptation of the whereHas() method in Laravel but I am not sure how to implement a filter or a date search on a relationship like this.

Thanks!


Solution

  • $orders = Order::whereDoesntHave('support_ticket')
        ->orWhereHas('support_ticket', function($query) {
            $query->where('created_at', '>=', now()->subDays(45));
        })->get();
    

    Where "support_ticket" is the name of the relationship in your Order model. In this way you can retrieve the orders that doesn't have a support ticket or that have at least one and less than 45 days old.

    As you are in Laravel 5 maybe now() is not defined, then you can use:

    \Illuminate\Support\Carbon::now()