ImaFirinMahLazer
ImaFirinMahLazer

Reputation: 61

Laravel, sort model by latest created child relation

I've got two models - Ticket & Answer, Answer is child (belongs to) of the ticket model. The goal is to sort tickets by most recent answer by its date, so in the end tickets with the recent answers should displayed at the top of the list on the frontend.

How that can be achieved?

Upvotes: 0

Views: 188

Answers (1)

NoOorZ24
NoOorZ24

Reputation: 3222

There are 2 solutions:

1st

Using sub-query join. Very similar case is in Laravel documentation so you can copy - paste - edit it. https://laravel.com/docs/8.x/queries#subquery-joins

2nd

You can update Ticket timestamps and order by that again similar to documentation: https://laravel.com/docs/8.x/eloquent-relationships#touching-parent-timestamps

Upvotes: 1

Related Questions