mix359
2 years ago

Order by eager loaded colum

Posted 2 years ago by mix359

Hi to all,

I'm having some trouble finding the right/best way to do one thing:

I've some case where I need to do the sorting based on a column that is loaded through eager loading. Here an example:

Account (id, name, surname) <-> Teacher (account_id)

Teacher::with('account')->orderBy('surname');

Usually the eager loading work great in those situation, where I need to access the the surname or name data. But in this situation where I need to order the data using that column, it doesn't work.

I've searched on the other topics and I haven't found a way using only the eager loading. I've found some suggestion about joining the accounts table, something like that:

Teacher::with("account")->join('accounts', 'teachers.id', '=', 'accounts.id')->orderBy('surname', 'DESC')

That work for the sorting, but have two downside:

  • The data from accounts are loaded 2 times: first time from the joined query, and second time by the eager loading. Also, the data from the first query (the one with the join) is inserted into the Teacher model.
  • I need to know the real name of a table out of the Model (usually in the controller)

There's any way/trick to do the eager loading/with but loading the data through the join? Or any other way to do sorting in those situation of eager loading? Any other suggestion?

Thanks to all

byez

Please sign in or create an account to participate in this conversation.