LoginSignup
1
2

More than 5 years have passed since last update.

定義されたgetアクセサーでソートしたい

Last updated at Posted at 2017-12-06

以下、学生テーブルです。

students

 | ID | 名前 | 国語 | 数学 | 英語
 |-------------------------------
 | 1  | 一郎  | 99  | 78   | 66
 | 2  | 次郎  | 50  | 100  | 87
 | 3  | 三郎  | 88  | 91   | 87

DBに存在しないtotalアトリビュートを作成します。

App\Students.php

class Students extends Model
{
    protected $appends = ['total'];

    public function getTotalAttribute() {
        $japanese = $this->attributes['japanese'];
        $mathematics = $this->attributes['mathematics'];
        $english = $this->attributes['english'];
        return $japanese + $mathematics + $english;
    }
}

作成されたtotalアトリビュートでソートする

App\Http\Controllers\StudentController.php

class StudentController extends Controller
{
    public function index()
    {
        $students = Students::orderByRaw('(japanese + mathematics + english) desc')->paginate(10);
        return view('student.index', ['students'=> $students]);
    }
}

以上です。

1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2