KodaC's avatar
Level 1

Delete all Tickets with TicketMessage older than X

I have two models

Ticket with id, title, created_at, updated_at TicketMessage with id, ticket_id, ..., , created_at, updated_at

I would like to find all Ticket where the last TicketMessage is older than 2 months.

Is there a better solution then

$cutoffDate = Carbon::now()->subMonths(26);
$ticketsToDelete = Ticket::whereHas('ticketMessages', function ($query) use ($cutoffDate) {
    $query->select('ticket_id', DB::raw('MAX(created_at) as last_message_date'))
        ->groupBy('ticket_id')
        ->having('last_message_date', '<', $cutoffDate);
})->get();
0 likes
2 replies
tisuchi's avatar
tisuchi
Best Answer
Level 70

@kodac Does it work?


$cutoffDate = Carbon::now()->subMonths(2); // Get the cutoff date

$ticketsToDelete = Ticket::whereHas('ticketMessages', function ($query) use ($cutoffDate) {
    // Find tickets where the latest message is older than 2 months
    $query->where('created_at', '<', $cutoffDate)
          ->orderBy('created_at', 'desc')
          ->limit(1); // Ensures only the latest message is checked
})->get();
2 likes

Please or to participate in this conversation.