Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Codeigniter - Ordering active record alphabetically

Tags:

codeigniter

I was wondering if someone could help me out with something.

I have a bit of ajax that calls a function in my model.

But i cant seem to be able to order the output by 'model'.

Below the function im having trouble with

function get_models_by_brand($tree = null)
{
    $this->db->select('id, model');

    if($tree != NULL){
        $this->db->where('brand_id', $tree);
    }

    $query = $this->db->get('models');
    $models = array();

    if($query->result()){
        foreach ($query->result() as $model) {
            $models[$model->id] = $model->model;
        }
        return $models;
    } else {
        return FALSE;
    }
}
like image 980
BigJobbies Avatar asked Jun 04 '12 15:06

BigJobbies


1 Answers

From the documentation,

$this->db->order_by();

Lets you set an ORDER BY clause. The first parameter contains the name of the column you would like to order by. The second parameter lets you set the direction of the result. Options are asc or desc, or random.

$this->db->order_by("title", "desc"); 
// Produces: ORDER BY title DESC

You can also pass your own string in the first parameter:

$this->db->order_by('title desc, name asc'); 
// Produces: ORDER BY title DESC, name ASC

Or multiple function calls can be made if you need multiple fields.

$this->db->order_by("title", "desc");
$this->db->order_by("name", "asc"); 
// Produces: ORDER BY title DESC, name ASC
like image 99
Colin Brock Avatar answered Oct 02 '22 12:10

Colin Brock