How to create sorting with multilevel relationships in Aravel 5.4?

Asked

Viewed 96 times

0

I did a lot of research to find a solution, but I only found a few libraries that perform sorting with only 1 level.

$anuncios = Anuncio::with(['veiculo' => function($q){
        $q->orderBy('nome', 'asc');
    }]);

This way it is ordering only by the column "name", but I need to sort by the column of another table with relationship, for example, "vehicle.marque.name". There is a library that provides this operation or a code that could solve this problem?

  • Put these models in question and relationships.

  • Let’s assume that I have the following models: Countries, states and cities. I have a list of all cities in all countries. How to sort cities from country names?

1 answer

0

I advise you to do as follows.

$transformer = function(Anuncio $anuncio) {

$anuncios = $anuncio->veiculo->marca->nome;

 return $anuncios->orderBy('nome');
}

Obs. I don’t know how are your relationships, but I believe it is possible to arrive by advertising in name value.

  • Where would this function be? Inside the controller?

  • Yes, what I did was I took your code and I made a Collection, so it’s easier to work the data, in my understanding.

  • In a way, we will be ordering Collection and not Builder itself. Correct? Can’t this cause performance problems? Is there any example of how to do this ordering with paging?

  • From what I saw of the code should not be something too heavy, so soon this should solve, if it grows the ideal would be to break it in services. I would do so at least.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.