Craig Ward
Craig Ward

Reputation: 2485

Passing variables from Model to Model in codeigniter

I need to pass a variable to model, that model needs to send another back and use that variable to query a different model.

EG:

I have a product_ID which I send to the product model, From that I find out the supplier_ID. I want to grab that supplier_ID to the supplier model to get the supplier name.

How do you implement this in codeigniter?

Upvotes: 1

Views: 1469

Answers (5)

Nick Jennings
Nick Jennings

Reputation: 4044

Why wouldn't something like this work for you?

$s_id = $this->product_model->getSupplierID($p_id);
$s_name = $this->supplier_model->getSupplierName($s_id);

Seems very straightforward to me. Or, perhaps you could clarify which this approach doesn't achieve what you need?

Upvotes: 0

TerryMatula
TerryMatula

Reputation: 1264

Like kemp said, it sounds like a join would be your best bet:

// pass the $product_ID variable to the model
$this->db->select('supplier_tbl.supplier_name');
$this->db->from('supplier_tbl');
$this->db->join('product_tbl','product_tbl.supplier_ID = supplier_tbl.supplier_ID');
$this->db->where('product.tbl',$product_ID);
$query = $this->db->get();

Of course, if you have a reason to keep the models separate, this won't help.

Upvotes: 0

fire
fire

Reputation: 21531

Easiest way is to set it as a public variable (see visibility in OOP):

function blah() {
    public $product_id = 0;

    $this->load->model('Products');

    // Products model can set and access $this->product_id

    $this->load->model('Suppliers');

    // Suppliers model can also set and access $this->product_id
}

If you really wanted to in CI you could declare $product_id in your controller to make it truely global but I wouldn't do that personally for tidyness.

Upvotes: 0

Bella
Bella

Reputation: 3217

I would generally do something like this in my controller:

$this->load->model('Products');
$this->load->model('Suppliers');

$result = $this->Suppliers->get_supplier_name($this->Products->get_product_supplier($product_id));

Upvotes: 3

Matteo Riva
Matteo Riva

Reputation: 25060

I would do a join between the two tables and do one single query.

Upvotes: 1

Related Questions