【问题标题】:Order by an array by key in laravel在laravel中按数组键排序
【发布时间】:2018-10-22 10:52:01
【问题描述】:

我正在使用以下查询从下表中获取匹配的 ID,我将仅获得 student_id

有了这个student_id,我必须从students 表中找到匹配的行,然后我想从students 表中找到orderBy() 键(例如名称)。

我在student_mappingstudent 模型之间建立关系。

$mapps = Student_mapping::select('student_id');

if($request->session_id) {
    $mapps = $mapps->where('session', '=', $request->session_id);
}
if($request->class_id) {
    $mapps = $mapps->where('class_id', '=', $request->class_id);

    if($request->group_id) {
        $mapps = $mapps->where('group_id', '=', $request->group_id);

        if($request->section_id) {
            $mapps = $mapps->where('section_id', '=', $request->section_id);
        }
    }
}

$mapps = $mapps->get();

$students = [];

foreach($mapps as $map) {
    if($map->student)
    {
        $students[] = Student::find($map->student_id);
    }
}

我必须让$students->orderBy('name', 'ASC'),但我不能这样做。

【问题讨论】:

    标签: laravel sql-order-by


    【解决方案1】:

    你可以使用User::where('id', $map->student_id)->orderBy('name', 'ASC');这看起来没什么用,因为 id 无论如何都是独一无二的。

    另外,您的代码似乎会受到对数据库的多次调用的影响。

    您可以将查询简化为:

    $student_ids = $mapps->pluck('student_id');
    $students = Student::whereIn('id', $student_ids)->orderBy('name', 'ASC')->get();
    

    PS:Eloquent(模型)环绕 QueryBuilder。见example of ordering or groupby in the documentation

    【讨论】:

      【解决方案2】:

      这样查询会更快更好:

      $students = Student::whereIn('id', $mapps)->orderBy('id')->get();
      

      这将为您提供应按 ID 排序的所有学生的Collection。如果您希望它作为一个数组,请记住在集合上调用 ->toArray() 方法,但无论哪种方式,它都应该用作集合。

      【讨论】:

        【解决方案3】:
        $students = [];
        
        foreach($mapps as $map) {
            if($map->student)
            {
                $students[] = Student::find($map->student_id);
            }
        }
        

        by laravel 集合类see

        return   collect($student)->sortBy('name')->values()->all();
        

        【讨论】:

          猜你喜欢
          • 2019-01-30
          • 2021-09-03
          • 1970-01-01
          • 2020-07-02
          • 2015-09-18
          • 2019-03-27
          • 1970-01-01
          • 2021-12-29
          • 2018-09-12
          相关资源
          最近更新 更多