以下、学生テーブルです。
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]);
}
}
以上です。