Welcome Guest, Not a member yet? Register   Sign In
Ways to wrtie in Active Record
#1

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();
PurdyDesigns Website Design, Development. Also Including Web Hosting. Print Media, server deployment and management, and more!
Reply
#2

But remember method chaining needs PHP5.
http://www.codeigniter.com/user_guide/da...l#chaining

Reply
#3

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

And so does CI too.
Reply
#4

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(); 
Reply
#5

(This post was last modified: 12-12-2014, 05:08 PM by bclinton.)

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('')
Reply
#6

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.
Reply




Theme © iAndrew 2016 - Forum software by © MyBB