简体   繁体   中英

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!

$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()

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