CodeIgniter Forums
Ways to wrtie in Active Record - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: Using CodeIgniter (https://forum.codeigniter.com/forumdisplay.php?fid=5)
+--- Forum: Best Practices (https://forum.codeigniter.com/forumdisplay.php?fid=12)
+--- Thread: Ways to wrtie in Active Record (/showthread.php?tid=27)



Ways to wrtie in Active Record - Shawn P - 10-23-2014

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();



RE: Ways to wrtie in Active Record - Rufnex - 10-23-2014

But remember method chaining needs PHP5.
http://www.codeigniter.com/user_guide/database/active_record.html#chaining


RE: Ways to wrtie in Active Record - peterdenk - 10-23-2014

(10-23-2014, 01:35 PM)Rufnex Wrote: But remember method chaining needs PHP5.

And so does CI too.


RE: Ways to wrtie in Active Record - mwhitney - 12-12-2014

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(); 



RE: Ways to wrtie in Active Record - bclinton - 12-12-2014

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('')



RE: Ways to wrtie in Active Record - mwhitney - 12-15-2014

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.