A
A
Andrey Boychenko2019-06-05 16:25:31
Laravel
Andrey Boychenko, 2019-06-05 16:25:31

SortBy or OrderBy on Laravel relationship collection?

Good evening. There is a task of sorting of values, at selection from basis. In general, if I implement a one-to-one relationship, there are no problems, everything works. But I have an EAV template in my database. Each product belongs to a group of characteristics. Each characteristic has a position field, according to which I set the sorting priority. After that, each feature has a link to a value associated with the product. And these values ​​also have a position field.
Let's say I got the data from the database and do the sorting

$products->sortBy(function($q){
    return $q->relatedProduct->relatedSpecsGroup->position;
})

This will work if the "relatedSpecsGroup" relationship is one to one, but it's a "to many via" relationship, so this method won't work. I didn't find anything about this in the documentation.
It turns out that "relatedSpecsGroup" contains the characteristics associated with the product group. And each characteristic has a value, which in turn belongs to both the product and the characteristic.
relatedSpecsGroup for each product looks like this:
[
['id', 'title','position','relatedValue'=>['id','value','position']],
['id', 'title','position','relatedValue'=>['id','value','position']],
['id', 'title','position','relatedValue'=>['id','value','position']],
['id', 'title','position','relatedValue'=>['id','value','position']],
]

I need to sort by relatedValue values, but first, sort relatedSpecsGroup by position, thus setting the sort order for features, and only then for feature values.
How is this kind of sorting done? Is it possible to do such sorting at the request level, because it is much faster than the sortBy method on the collection. If not, how is it implemented using sortBy?
Thank you!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
J
jazzus, 2019-06-05
@jazzus

Try like this

Product::with(['relatedSpecsGroup' => function($query) {
              $query->orderBy('position', 'desc');
             }])
       ->orderBy('relatedValue', 'desc')
       ->get();

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question