Howard
Howard

Reputation: 3758

Using Laravel's Schema builder is there a way to do a ORDER BY FIELD query?

Is there a way to do a ORDER BY FIELD query? This is what I currently have.

$sets = DB::connection('mysql')
            ->table('sets')
            ->orderBy('type', 'asc')
            ->orderBy('releaseDate', 'asc')
            ->select('code', 'type', 'name')
            ->get();

Or do I have to write the MySQL directly?

Upvotes: 1

Views: 73

Answers (1)

msturdy
msturdy

Reputation: 10794

You can use DB::raw() to insert your ORDER BY FIELD clause:

$sets = DB::connection('mysql')
        ->table('sets')
        ->orderBy(DB::raw('FIELD(type, "Banana", "Apple", "Orange", "Peach", "Grape")'))
        ->select('code', 'type', 'name')
        ->get();

Beware of SQL injection of course... And to check what the final SQL is, you can use the Query Log after running the SQL:

$query_log = DB::getQueryLog();

Upvotes: 1

Related Questions