laravel 循环添加新的数据之后如何排序

例子

解释写在注释中

$school_id = $this->getSchoolId($user);
        $clubs = Club::where('school_id', '!=', $school_id)
            ->get(['id', 'name', 'school_id', 'logo_img'])
            ->take(6)
            ->each(function ($club) {
                #添加的两条新数据 
                $club->school_name = $club->school()->value('sch_name');
                $club->order_score = $this->getAllOtherSchoolClubOrder($club->id);//得到分数用于排序
            });
        $clubs = collect($clubs)->sortByDesc('order_score')->toArray();//先进行倒叙排序
        $clubs = array_values($clubs);//虽然排序了但是前端取数据的时候依然是安装key进行取值所以这里清除key,使用array_values();函数只取值
        return $clubs;
posted @ 2021-04-22 11:29  以己为镜  阅读(159)  评论(0编辑  收藏  举报