CakePHPでwhere句のINの並び順で結果をsortしたいときはORDER BY FIELDを使う

where句のINの並び順で結果をsortしたいときはORDER BY FIELDを使うの続き

findのorderの所で

<?php
array('order' => array('FIELD(Country.id, 4, 1, 5, 3, 6, 2)'))

と書けばいい。

参照

http://cakebaker.42dh.com/2008/06/10/order-by-field/

Ok, let’s do some examples to learn more about it. We will use the following countries table:
[1] => USA
[2] => Germany
[3] => Russia
[4] => Austria
[5] => China
[6] => Switzerland
Now, we don’t want to sort them by the id, but by some “strange” order: Austria, USA, China, Russia, Switzerland, Germany. For this purpose we can use “order by field”: the first parameter is the column name and all following parameters are values of the respective column. In CakePHP it is done in the following way:

<?php
$this->Country->find('list', array('order' => array('FIELD(Country.id, 4, 1, 5, 3, 6, 2)')));

And we get the expected result:
[4] => Austria
[1] => USA
[5] => China
[3] => Russia
[6] => Switzerland
[2] => Germany