CodeIgniter Forums

Full Version: Ways to wrtie in Active Record
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
While the documentation shows you can write code like:

Code:
$this->db->where();
$this->db->get()
$this->db->get_where();

You can also write more clean code with a lot less typing like below:

Code:
$my_query = $this->db
      ->where('')
      ->where_in('')
      ->select('')
      ->from('')
      ->order_by('')
      ->limit('')
      ->get();
But remember method chaining needs PHP5.
http://www.codeigniter.com/user_guide/da...l#chaining
(10-23-2014, 01:35 PM)Rufnex Wrote: [ -> ]But remember method chaining needs PHP5.

And so does CI too.
Depending on context, I sometimes find it cleaner, especially with long chains, to do something like this:
PHP Code:
$this->db->select('')
 
        ->from('')
 
        ->where('')
 
        ->where_in('')
 
        ->order_by('')
 
        ->limit('');

// Maybe there is more code here to modify the query

// Finally, assign the result to the $my_query variable

$my_query $this->db->get(); 
I personally don't find chaining any clearer.  For more complex queries I like blank lines between my select, join, order_by, etc statements for code clarity so chaining is not an option


Code:
$this->db->select('');
$this->db->select('');

$this->db->from('')

$this->db->where('')

$this->db->order_by('')

$this->db->limit('')
What I usually do is start with the SQL I want to generate, e.g.:

Code:
select a, b, c
from tablename
where a = 1

Then I transfer that to my model:

PHP Code:
$this->db->select(array('a''b''c'))
         ->
from('tablename')
         ->
where('a'1);

// and set my result to a variable or do something else with it:
$query $this->db->get(); 

In most cases, whether I choose chaining for a particular portion of the query depends on the complexity of that portion (e.g. if the interior of the select/where/etc. method spans multiple lines).

If part of my query is conditional, I've recently started leaning towards making additional calls to $this->db methods rather than using variables to set the arguments to those methods in a large chain, so I'm comfortable with both, but won't call $this->db multiple times unless using a single call requires jumping additional logic or variables.