我有一些问题与laravel sortBy(laravel 5.4)..根据我在许多网站上阅读的内容,它说,做多次sortBy laravel是通过使用逆序..所以我尝试这样做..但仍然不能正常工作..
所以这里是...... 我有这个对象的集合......
[{
'product_id' => 468,
'name' => 'abc',
'int_premi' => 10000
'score' => 1000
'rates' => 0,
'views' => 0,
'promo' => null
},{
'product_id' => 472,
'name' => 'bcd',
'int_premi' => 10000
'score' => 1000
'rates' => 0,
'views' => 0,
'promo' => 'Some text here'
},{
'product_id' => 458,
'name' => 'def',
'int_premi' => 10000
'score' => 1000
'rates' => 0,
'views' => 0,
'promo' => 'ABC'
}]
我的目标是按照此顺序对此对象进行排序
得分(asc)> int_premi(asc)>费率(desc)>促销(如 boolean)(desc)>观点(desc)> product_id(desc)
所以我写这段代码..
$collection->sortByDesc('product_id')->sortByDesc('views')->sortByDesc(function($arr,$k){
return !empty($arr->promo);
})->sortByDesc('rates')->sortBy('int_premi')->sortBy('score')->values()->all()
我正在寻找此订单的结果
BCD> DEF> ABC
相反,不遵循该命令..
那么是否有人也面临同样的问题?也许有人可以帮我解决这个问题?
非常感谢
答案 0 :(得分:0)
做了一些研究后......我发现一个正在研究.. 如果你面对同样的事情......这篇文章可能有所帮助..
https://www.jjanusch.com/2017/05/laravel-collection-macros-adding-a-sortbymuti-function
所以我的决定与本文的建议完全相同,通过创建一个宏......就像这样
if (!Collection::hasMacro('sortByMulti')) {
/**
* An extension of the {@see Collection::sortBy()} method that allows for sorting against as many different
* keys. Uses a combination of {@see Collection::sortBy()} and {@see Collection::groupBy()} to achieve this.
*
* @param array $keys An associative array that uses the key to sort by (which accepts dot separated values,
* as {@see Collection::sortBy()} would) and the value is the order (either ASC or DESC)
*/
Collection::macro('sortByMulti', function (array $keys) {
$currentIndex = 0;
$keys = array_map(function ($key, $sort) {
return ['key' => $key, 'sort' => $sort];
}, array_keys($keys), $keys);
$sortBy = function (Collection $collection) use (&$currentIndex, $keys, &$sortBy) {
if ($currentIndex >= count($keys)) {
return $collection;
}
$key = $keys[$currentIndex]['key'];
$sort = $keys[$currentIndex]['sort'];
$sortFunc = $sort === 'DESC' ? 'sortByDesc' : 'sortBy';
$currentIndex++;
return $collection->$sortFunc($key)->groupBy($key)->map($sortBy)->ungroup();
};
return $sortBy($this);
});
}
然后你可以像这样在你的收藏中使用它
$collection->sortByMulti([
'prop_one' => 'ASC',
'prop_two' => 'ASC',
etc....
]);
prop_one和prop_two是你的收藏属性.. 希望这个帮助