【问题标题】:Passing variables from Model to Model in codeigniter在codeigniter中将变量从模型传递到模型
【发布时间】:2011-03-01 13:31:12
【问题描述】:

我需要将一个变量传递给模型,该模型需要发回另一个变量并使用该变量来查询不同的模型。

EG:

我有一个 product_ID 发送给产品模型,从中我可以找到供应商 ID。我想将供应商 ID 抓取到供应商模型以获取供应商名称。

如何在 codeigniter 中实现这一点?

【问题讨论】:

    标签: php model-view-controller codeigniter variables


    【解决方案1】:

    我通常会在我的控制器中做这样的事情:

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

    【讨论】:

    • 我需要从“产品”中获取一个值以发送给“供应商”,我尝试使用类似$this->products_model->get_products($p_id, &$b_id); p_id 是我发送以获取正确信息的产品 ID,而 b_id 是什么我要回来
    【解决方案2】:

    我会在两个表之间进行连接并执行一个查询。

    【讨论】:

      【解决方案3】:

      最简单的方法是将其设置为公共变量(参见 OOP 中的 visibility):

      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 以使其真正具有全局性,但为了整洁,我不会亲自这样做。

      【讨论】:

        【解决方案4】:

        就像 kemp 所说,听起来加入是你最好的选择:

        // 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();
        

        当然,如果您有理由将模型分开,这将无济于事。

        【讨论】:

          【解决方案5】:

          为什么这样的东西不适合你?

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

          对我来说似乎很简单。或者,也许您可​​以澄清一下这种方法不能满足您的需要?

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多