Search code examples
sql-order-bykohanabuilder

Kohana Database Query Builder custom sort order ("ORDER BY Field (id, 1, 3, 2)" in MySQL)


I have a set of id's to select, so I request:

$ids = array( 1, 2, 3, 4, 5 );
$q = DB::select('field1', 'field2', 'field3')->
     from('work')->
     where('field1', 'in', $ids)->execute();

How can I sort them in my custom order, like MySQL's 'ORDER BY Field' do?


Solution

  • Check out DB::Expr

    You can use it like so:

    ->order_by(DB::Expr('FIELD(`field`, 3,1,2)'))
    

    Note, you'll have to manually escape the contents