Mysql Codeigniter Active Record - How do I do a wh

2019-04-09 00:33发布

问题:

I have a set of IDs passed in a particular order which needs to be retained. I am querying from several left joins the data related to each ID. The IDs are returned from a search so the order must be kept to make the results valid (otherwise it makes searching rather pointless).

My code looks something like;

$this->db->where_in('id', $array_of_ordered_ids);

For example -

$this->db->where_in('id', array(4,5,2,6));

Will return the results in order 2,4,5,6.

I'd like for it to retain the order and return the results 4,5,2,6.

Thank you,

回答1:

To order the result by the order in your array, you can do the following:

$array_of_ordered_ids = array(4,5,2,6);

As you already know the order of the numbers, you can use the Mysql FIELD()Docs function:

ORDER BY FIELD(id, 4, 5, 2, 6);

To create such a string, you can use implodeDocs:

$order = sprintf('FIELD(id, %s)', implode(', ', $array_of_ordered_ids));

Give it a try:

$array_of_ordered_ids = array(4,5,2,6);
$this->db->where_in('id', $array_of_ordered_ids);
$order = sprintf('FIELD(id, %s)', implode(', ', $array_of_ordered_ids));
$this->db->order_by($order); 


回答2:

As all answers I found on SO where just semi correct but all gave good hints I implemented successfully the code to retrieve set of rows correct ordered by the order in given array.

To Produce a sql like this:

SELECT * FROM (`product`) WHERE `id` IN (2, 34, 234) 
ORDER BY FIELD(`id`, 2, 34, 234)

use this code, while $ids contains the array (2, 34, 234).

// select from ... 
$this->db->where_in('id',$ids);
$this->db->_protect_identifiers = FALSE; // stop CI adding backticks
$order = sprintf('FIELD(id, %s)', implode(', ', $ids));
$this->db->order_by($order);
$this->db->_protect_identifiers = TRUE; // switch on again for security reasons
// get...

see also here: http://ellislab.com/forums/viewthread/137157/#1058666



回答3:

Thank for biggest solution.

 $orde_num_string = implode(",",$order_num);
            $this->db->where_in("cir_order.order_num",$order_num);
            $this->db->_protect_identifiers = FALSE;
            $this ->db->order_by("FIELD(cir_order.order_num, $orde_num_string)");
            $this->db->_protect_identifiers = TRUE;