Welcome Guest, Not a member yet? Register   Sign In
Where insert loop? Controller or model?
#1

Hi!

Which way to put the loop will be better?

Controller
PHP Code:
for ( $i=0$i $MaxI$i++ ) { 
    
$variable[] = $this->Name_model->GetItem();



Model
PHP Code:
for ( $i=0$i $MaxI$i++ ) { 
    
$this->db->where'Name''My Name' );
    
$result[] = $this->db->get();

Reply
#2

Whatever works for you. Most of the time it's best to minimize the amount of code in the controller.
Simpler is always better
Reply
#3

the problem is if you get an error its not going to be fun trying to figure it out.
So make an array first (which maybe you need a loop for)
PHP Code:
$names = array('Frank''Todd''James'); 

then use that array to get your database results.  
PHP Code:
$this->db->where_in('name'$names); 

example is from the codeigniter user guide
http://www.codeigniter.com/user_guide/da...ilder.html
Reply
#4

Hi,

I would put it in the controller initially.

Later, if you find you need to reuse it in multiple controllers, put it in a model or a library.

I almost always now find it quicker to first code in the controller, then later move sections into models or libraries.

Best wishes,

Paul.
Reply
#5

As far as best practices go, I see three different considerations here:

1) Calls to $this->db belong in the model
2) Querying the database inside a loop should be avoided
3) An extension of #2 is that calling the model inside a loop should be avoided

#2 is accomplished largely with something like the solution cartalot provided. Build an array of arguments in your loop, then use where_in() instead of where().

#3 is often a matter of figuring out where you need to add functionality to your model to handle bulk operations like this.

In most cases, I end up solving all of these problems the way PaulD suggests, with one exception: when I need to call the database, I build a model right away (unless I already have a model for that data). If I need to do something a little more complex with the data, I might work through it in the controller before moving it to the model, but I really try not to leave a call to $this->db in the controller any longer than is strictly necessary.

If I find myself calling my model in a loop inside my controller, I might spend a little more time determining whether I really have a performance need for moving the loop into the model, but, in the end, it's pretty rare that it wouldn't be possible to improve performance by doing so (since calling the model in a loop usually results in querying the database in the loop).
Reply




Theme © iAndrew 2016 - Forum software by © MyBB