Aaron Alfonso
Aaron Alfonso

Reputation: 516

Codeigniter: Customize ordering query

I want to achieve doing ORDER BY task_status = 'Open' but I am unable to get the result.

I did this

$this->db->from('session_tasks');
$this->db->order_by('task_status', 'OPEN', 'DESC');        
$query = $this->db->get();

I hope anyone can help.

Upvotes: 0

Views: 1901

Answers (3)

Rohan Kumar
Rohan Kumar

Reputation: 40639

Try this,

 $this->db->query("SELECT * FROM session_tasks
         ORDER BY task_status = 'OPEN' DESC,task_status ASC"); 

Alternatively,

$this->db->query("SELECT * FROM session_tasks
         ORDER BY CASE WHEN task_status = 'OPEN' THEN 0 ELSE 1 END ASC,
         task_status ASC"); //Ordering starts with Open, then in Ascending order

Here is one more solution using Codeigniter active record that works. Note the usage of double quotes when using string literal.

$this->db->_protect_identifiers = FALSE;
$this->db->from('session_tasks');
$this->db->order_by("task_status = 'OPEN'", 'DESC');
$this->db->order_by('task_status');
$query = $this->db->get();
$this->db->_protect_identifiers = TRUE;

Upvotes: 3

Tomasz
Tomasz

Reputation: 5162

You can do this like this:

// set this to false so that _protect_identifiers skips escaping:
$this->db->_protect_identifiers = FALSE;

// your order_by line:
$this -> db -> order_by('FIELD ( products.country_id, 2, 0, 1 )');

 // important to set this back to TRUE or ALL of your queries from now on will be non-escaped:
$this->db->_protect_identifiers = TRUE;

Source

Upvotes: 0

parth
parth

Reputation: 1868

use this code

$this->db->order_by("task_status", "desc");
$query = $this->db->get_where('session_tasks', array('task_status'=>'open'));

to check the documentation click here

Upvotes: 0

Related Questions