4

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?

double-beep
  • 5,031
  • 17
  • 33
  • 41
1allen
  • 43
  • 1
  • 7

1 Answers1

7

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

SpadXIII
  • 906
  • 4
  • 5
  • 2
    Good answer, but actually you can just use `->order_by('FIELD("id", 1, 2, 3)')`, no need for DB::expr. Still need to escape the field values properly though, which could be done with `->order_by('FIELD("id", :f1, :f2)')->param(':f1', $f1)->param(':f2', $f2)`. – shadowhand Feb 26 '11 at 00:59
  • Indeed, I (kind of) forgot about that; that's what you get for working on non-kohana projects for too long.. – SpadXIII Feb 26 '11 at 14:57
  • 1
    you definitely need DB::expr, if you use table prefixes. – 1allen Mar 01 '11 at 02:20