我需要將一個變量傳遞給模型,該模型需要發送另一個回來並使用該變量來查詢不同的模型。將模型中的變量傳遞給codeigniter
EG:
我有一個PRODUCT_ID我發送到產品模型,從我找出supplier_ID。我想要將該supplier_ID獲取到供應商模型以獲取供應商名稱。
你如何在codeigniter中實現這一點?
我需要將一個變量傳遞給模型,該模型需要發送另一個回來並使用該變量來查詢不同的模型。將模型中的變量傳遞給codeigniter
EG:
我有一個PRODUCT_ID我發送到產品模型,從我找出supplier_ID。我想要將該supplier_ID獲取到供應商模型以獲取供應商名稱。
你如何在codeigniter中實現這一點?
我一般會做這樣的事情在我的控制器:
$this->load->model('Products');
$this->load->model('Suppliers');
$result = $this->Suppliers->get_supplier_name($this->Products->get_product_supplier($product_id));
我會做兩個表之間的連接,並做一個單一的查詢。
最簡單的方法是將其設置爲公共變量(見visibility在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
}
如果你真的想在CI,你可以在你的控制器聲明$ PRODUCT_ID,使其忠實地全球化,但我不會爲了整潔而親自去做。
像坎普說,這聽起來像一個加入將是你最好的選擇:
// 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();
當然,如果你有一個理由讓模型分開,這不會幫助。
爲什麼不會像這樣對你有用?
$s_id = $this->product_model->getSupplierID($p_id);
$s_name = $this->supplier_model->getSupplierName($s_id);
看起來很直截了當。或者,也許你可以澄清哪種方法不能達到你所需要的?
我需要從 '產品' 得到的值發送到 '供應商', 我嘗試使用類似 '$這個 - > products_model-> get_products($的p_id,&$ B_ID);' p_id是我發送的產品ID以獲取正確的信息,b_id是我想要的 – 2010-06-09 09:39:13