본문 바로가기
laravel

라라벨 쿼리빌더 정렬

by dev정리 2024. 7. 2.

기본 정렬

use Illuminate\Support\Facades\DB;

// 이름을 기준으로 오름차순 정렬
$employees = DB::table('employees')->orderBy('name', 'asc')->get();

// 이름을 기준으로 내림차순 정렬
$employees = DB::table('employees')->orderBy('name', 'desc')->get();

 

다중 열 정렬

use Illuminate\Support\Facades\DB;

// 먼저 'position' 기준 오름차순, 다음으로 'name' 기준 내림차순 정렬
$employees = DB::table('employees')
    ->orderBy('position', 'asc')
    ->orderBy('name', 'desc')
    ->get();

 

랜덤 정렬

use Illuminate\Support\Facades\DB;

// 랜덤 정렬
$employees = DB::table('employees')->inRandomOrder()->get();

 

사용자 정의 정렬

use Illuminate\Support\Facades\DB;

// 특정 순서로 정렬
$employees = DB::table('employees')
    ->orderByRaw("FIELD(position, 'Manager', 'Developer', 'Designer')")
    ->get();

 

문자열 길이 기준 정렬

use Illuminate\Support\Facades\DB;

// 이름의 길이를 기준으로 오름차순 정렬
$employees = DB::table('employees')
    ->orderByRaw('LENGTH(name) asc')
    ->get();

 

복잡한 사용자 정의 정렬

use Illuminate\Support\Facades\DB;

// 복잡한 사용자 정의 정렬
$employees = DB::table('employees')
    ->orderByRaw('(salary * 1.2 - bonus) desc')
    ->get();