Laravel Eloquent - 按照数组顺序对集合按列排序

3
我希望能够按照特定顺序根据状态列对我的集合结果进行排序。
我的想法是对集合进行分页,但以特定顺序为优先级:[2, 1, ...],这样就可以先显示待处理列表,然后再显示其他列表!
是否有人知道这种方法?
提前感谢您。

1
发布你的集合代码,它是什么样子的 - undefined
这个回答解决了你的问题吗?通过ID数组对Laravel集合进行排序 - undefined
@miken32谢谢回复,麻烦你看一下下面标记的答案,正是我想要的:D - undefined
2个回答

8

如果您的状态优先级不是按数字顺序排列的(例如,2> 1> 3> 0),您可以通过向sortBy传递回调函数来实现排序:

$collection = collect([
    ['name' => 'A', 'status' => 0],
    ['name' => 'B', 'status' => 3],
    ['name' => 'C', 'status' => 0],
    ['name' => 'D', 'status' => 1],
    ['name' => 'E', 'status' => 2],
    ['name' => 'F', 'status' => 1],
    ['name' => 'G', 'status' => 3],
    ['name' => 'H', 'status' => 1],
    ['name' => 'I', 'status' => 2],
    ['name' => 'J', 'status' => 3],
]);

// define status priority here
$statusPriorities = [2, 1, 3, 0];

$collection->sortBy(function($order) use($statusPriorities){
   return array_search($order['status'], $statusPriorities);
})->values()->all();

输出:

[
     [
       "name" => "I",
       "status" => 2,
     ],
     [
       "name" => "E",
       "status" => 2,
     ],
     [
       "name" => "D",
       "status" => 1,
     ],
     [
       "name" => "F",
       "status" => 1,
     ],
     [
       "name" => "H",
       "status" => 1,
     ],
     [
       "name" => "B",
       "status" => 3,
     ],
     [
       "name" => "G",
       "status" => 3,
     ],
     [
       "name" => "J",
       "status" => 3,
     ],
     [
       "name" => "A",
       "status" => 0,
     ],
     [
       "name" => "C",
       "status" => 0,
     ],
   ]

我该如何使用Eloquent(模型)和分页来实现这个功能呢? - undefined
重要提示:当优先顺序列表中未列出所有可能的值时,请使用in_array函数,否则未找到的值将位于列表开头。 - undefined

1
参考laravel文档https://laravel.com/docs/7.x/collections#method-sortby,您可以按列对集合进行排序...
$tasks = App\Task::all();
$tasks1 = $tasks->sortBy('title');
return $tasks1->values()->all();
//values() method is used to preserve array original keys
//You can also user sortByDesc, to get reverse order of your collection.

正如您所看到的,它已经按标题升序排序。
[
    {
        "id": 5,
        "title": "Akhtar",
        "created_at": "2019-09-01 14:18:05",
        "updated_at": "2019-09-01 14:18:05"
    },
    {
        "id": 6,
        "title": "Hamid khan",
        "created_at": "2019-09-01 14:18:05",
        "updated_at": "2019-09-01 19:19:18"
    },
    {
        "id": 7,
        "title": "Zarif",
        "created_at": "2019-09-04 19:14:18",
        "updated_at": "2019-09-04 19:14:18"
    },
    {
        "id": 1,
        "title": "testing",
        "created_at": "2019-09-01 13:01:39",
        "updated_at": "2019-09-01 13:01:39"
    }
]

我很感谢你的建议,但是这个答案不符合我的要求! - undefined
这和上面的答案完全一样。但没关系,不是问题。 - undefined
这不是的,想法是使用一个数组来设置该列的优先级顺序... @CBrach回答得非常完美! - undefined
我也是这样做的,我正在编辑我的答案。但没关系,亲爱的。 - undefined

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接