简体   繁体   English

在Laravel中求和后如何从高到低排序?

[英]How to sort from highest to lowest after sum the value in Laravel?

I am new to Laravel.我是 Laravel 的新手。 Right now, I am having a difficulty on how to sort students' name from highest to lowest based on their total marks.现在,我在如何根据学生的总分从高到低对他们的名字进行排序时遇到了困难。 Below are my data from the Postman.下面是我从邮递员那里得到的数据。

{ 
  "score": [
    {
        "name": "Adam",
        "sex": "male",
        "totalMarks": 250
    },
    {
        "name": "Lisa",
        "sex": "female",
        "totalMarks": 350
    },
    {
        "name": "Daniel",
        "sex": "male",
        "totalMarks": 300
    },
    {
        "name": "Mary",
        "sex": "female",
        "totalMarks": 330
    },
    {
        "name": "Sarah",
        "sex": "female",
        "totalMarks": 280
    }
  ]
}

Below is my code from ScoreController.php下面是我来自 ScoreController.php 的代码

$class_id = $user->class->id;
$students = Students::whereIn('class_id', $class_id)->get();
$score = array();

foreach ($students as $student) {
   array_push($score, [
      'name' = $student->name,
      'sex' = $student->sex,
      'totalMarks' = $student->subjects->sum('mark'),
   ]);
}

return response()->json([
  'score' => $score,
]);

I would like to sort student based on sum of the mark .我想根据mark总和对学生进行排序。 So a student with a highest totalMarks should be at the top of the list.所以totalMarks最高的学生应该排在榜首。 Thank you in advance.先感谢您。

Using eloquent attributes will probably do you good here.在这里使用 eloquent 属性可能对你有好处。 In your Students class add an eloquent mutator .在您的 Students 类中添加一个 eloquent mutator

class Students {
    // to include it in the response.
    $with = ['totalMarks'];

    public function getTotalMarksAttribute() {
        return $this->subjects->sum('mark');
    }
}

Now you can optimize your original code a bit.现在您可以稍微优化您的原始代码。 You don't have to transform your objects into an array, with this approach.使用这种方法,您不必将对象转换为数组。

$students = Students::whereIn('class_id', $class_id)
    ->get()
    ->sortByDesc('totalMarks');

// laravel will automatic transform the objects, an way more maintainable approach
return response()->json([
  'score' => $students,
]);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM