I am using the EAV pattern in my DB. It's mean that I have a product, that belongs to a lot of specifications, and the specifications belong to a lot of specification values.
I need to sort my product by the condition. For example, my products have specifications group. A product like iPhone 6 has a "phone" group and the "phone" group has specifications like display, RAM, Storage. All of these specifications have a position column like RAM (POS 1), Storage (POS 2), Display(Pos 3). Inside every specifications, a lot of values and every value have position column too.
So when I fetching all my products, every product has relations with the group. I am using eloquent relations hasManyThrough to get all specifications which are connected to the group.
It's how my collection looks like: https://pastebin.com/8TAM62wt
According to example, I need to sort my position by specification value, but values should get by position column specifications table. My English isn't good, so I will provide one more example.
Here in this code https://pastebin.com/QnC7Drq3
I need to sort all products by specification values where specifications table have title Display because its position is 1. So I sorted my product by the display, then I go to the next specification with higher position value. According to this example, it would be Storage, cause position is 3.
I know the only one way, how to sort, and it's work when relatedSpecifications is an array (collection), but not work when it's array an of array.
$products = ModelProvidersProducts::has('relatedProduct')->where('quantity', '!=', 0)->get();
$products->sortBy(function($q){
return $q->relatedProduct->relatedSpecifications->position;
});
I hope that my English is enough to describe my problem. Hopes some of you guys can help me or at least show the right way to go.
Also, I understand that sorting a collection is way slowly, then orderBy, maybe it's better if you can give an example with orderBy, not sortBy?
You can chain sort By to achieve this
$products->sortBy(function($q){
return $q->relatedProduct->relatedSpecifications->position;
})->sortBy(function($q){
return $q->relatedProduct->relatedSpecifications->somethingelse;
});