Sort by relation table

I’m creating a chat service, I have 2 tables “chat” and “message”:

chat - contain the default data about the conversation

message - contain all the messages for a determined chat

I create a CRUD and on the index action I want to sort the all the chats by the last updated, to do that I need to check for each chat for the id on the message table.

Now I have a dataprovider like this:

$dataProvider = new ActiveDataProvider([

            'query' => Chat::find(),


How can I get all the chats order by the messages ids?

For example I create the chat 1, chat 2 and chat 3 for this order. but is the chat 2 was the last to get an messages it will appear first on my list.

its very easy u can use join query nd then order by messageid.

Thank you.

I solve my problem with this guide -