Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Andulka_IT's avatar

Sorting through many tables problem

Hi guys,

I'm doing a table sort and one of the columns that I need to sort has data that are located in a different table. Table that contains data to sort is through three relations away. The issue is that the sort takes too long, so the result is a timeout.

There are relationships: Model 1 => hasManyThrought => Model 2, Model 3 Model 3 => belongsTo => Model 4 (my field)

And I need to sort data in Model 1 by column in Model 4.

I have all relationships loaded with eager loading. I tried to sort it as the collection (sortBy, sortByDesc), and I tried to sort them by raw SQL. What do you think is the best option? What if there are more of those columns?

Thank you

0 likes
4 replies
SilenceBringer's avatar

@andulka_it

Model 1 => hasManyThrought => Model 2, Model 3

so, Model 1 can have many Model 4. Which one you want to sort by?

1 like
SilenceBringer's avatar

@Andulka_IT I understand it. but think about your explanation: model 1 HASMANYthrough Model 2 and 3. So, it total Model 1 has many associated Model 4 via intermediate models, right? like, for example, Model 1 have assocaited Model 4a, Model 4b and Model 4c via tables 2 and 3. And the question is which of models (4a, 4b or 4c) must be used for sorting?

sr57's avatar

@andulka_it

The issue is that the sort takes too long

Can depend of many things, you don't give us any metrics ....

If you setup the right indexes and have a very large table you can/have to replicate the sorting field from Model4 to Model1.

Doing this, even if your table is no so large, will help you to understand what @silencebringer explained to you.

1 like

Please or to participate in this conversation.