Welcome Guest, Not a member yet? Register   Sign In
how to load a model within a foreach
#1

[eluser]dcallan[/eluser]
$this->load->model('bll/Product_bll');

foreach ($query->result() as $row)
{
$basket_array[$count]['unitPrice'] = $row->unitPrice;
$basket_array[$count]['quantity'] = $row->quantity;
$basket_array[$count]['product'] = $this->Product_bll->getProduct($row->itemCode);

$count++;
}

return $basket_array;

What is the correct way to load a model within a foreach block. I'd normally load a model with $this-MODELNAME->MODELFUNCTION but from within the context of a foreach I think $this is taken to be the current looping row so my question is what way should I be looping a model within a foreach?

thanks in advance.
#2

[eluser]Rok Biderman[/eluser]
I don't know how to do it, but it seems to me it's not supposed to work that way. I really can't imagine a circumstance where i'd want to do that, because it is sure to put considerable unnecessary strain on the database. As far as I can see, you're not doing anything that could not be done with a simple join in the original model. Just my 2c, more experienced than me might suggest something else.
#3

[eluser]dcallan[/eluser]
Hey thanks for the reply, I didn't want to go a join as getProduct is a function needed by other parts of the system in its own right, so I thought why not just use what I have elsewhere... I'm trying to build my system without any joins as I believe that's they way active record/active pattern is too work.. it's a small system so its probably doesn't matter much either way.

I got it working though, what I had to do was access it through the main CI object so in
the model method where I wanted to call another separate model I had this

$CI =& get_instance(); $CI->load->model('bll/Product_bll');

and then access it with this:

$CI->Product_bll->getProduct($row->itemCode);

I tried to put the get_instance line into my containing model but getting reference errors, but anyhow it works if its in the actual containing method, maybe there's a cleaner way to do this, I'm not sure.

cheers.
#4

[eluser]Rok Biderman[/eluser]
Ah, I didn't realize that. I'd always done this by calling another method in my controller, but i see now how it could be used. Good to know anyway. Doubt you could get much cleaner than that.
#5

[eluser]dcallan[/eluser]
I think 'they' say that you should keep controller thin and model fat.. so that's another reason for doing in model.




Theme © iAndrew 2016 - Forum software by © MyBB