T
T
TERRAN472017-05-27 22:00:39
Laravel
TERRAN47, 2017-05-27 22:00:39

How to sort json field by element in it?

Good afternoon, You need to display the list by "hero_win_rate" who is in first place, and so on, I'm racking
my brains on how to sort the json field.
Hero::orderBy(hero_count_wins, 'desc')->orderBy(hero_win_rate, 'desc')->get();
this is how the fields in the table are sorted clearly,
but how to sort a field with a json extension with an object in it: {"hero1":[{"name_hero":"KOLOBOK","win_rate":"54%"}],"hero2":[ {"name_hero":"ZAIKA","win_rate":"50%"}]}
where I will need to sort by win_rate,
I need to somehow enter the json field of each user, sort and return))) with all fields other id ...
for each user, I also don’t want to create 25 heroes, for example,
how would you do it? on Laravel

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Andrzej Wielski, 2017-05-27
@wielski

https://laravel.com/docs/5.4/collections

$array = json_decode(..., true);
$sorted = collect($array)->sortBy(function ($hero, $key) {
    return collect($hero)->sum('win_rate');
})->all();

Something like this.
You may have to rewrite for your structure, but the essence is clear.

V
Vitaly Yushkevich, 2017-05-31
@yushkevichv

You can also try at the DB level https://laravel.com/docs/5.4/queries#json-where-clauses by analogy.
Just need the field to be json. Support has appeared since recent versions.
Otherwise, then sort the results by collection, as you were told above

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question