0

I have an issue with datamapper orm and codeigniter.

I have an array with person names:

$names = array('john t', 'alex f', 'martin a');

Now I want to get all person who have this name:

$persons = new Person();
$persons->where_in('name', $names);
$persons->get();

My Question is just how can I sort person objects like my array ? If I echo persons the sorting is just other than my array.

I know there is a way to order_by columns for example $persons->order_by('id DESC');

TY.

John Smith
  • 47
  • 8

1 Answers1

0

If you are on MySQL you could use the FIELD() method for this, in SQL:

select * from persons where name in ('foo', 'bar', baz') order by field(name, 'bar', 'baz', 'foo');

You can use case with a bunch of when too if you are on postgres or other dbms, see some ideas here.

However the order_by methods in codeigniter (the datamapper on just forwards the call to it) will try to escape it's parameters so you will end up having an sql error. You can hack around this by directly manipulating the array where the order by strings are stored like this.

// before the ->get();
$person->db->ar_orderby[] = "field(name, 'john t', 'alex f', 'martin a')";

You need to be extremely careful to escape your input here and to match the column name (in the example name) since you have no help from the framework anymore.

complex857
  • 20,425
  • 6
  • 51
  • 54