【问题标题】:Codeigniter Query Builder dispatched in several functionsCodeigniter Query Builder 在多个函数中调度
【发布时间】:2017-04-02 08:33:44
【问题描述】:

我正在使用 Codeigniter 3.0.3。 我想用查询构建器构建一个查询,但是将我的查询构建拆分为几个函数。 例如:

 class MyCart{

 public function __construct() {
    $this->db->select('A.id, A.title, A.price');
    $this->db->from('articles A');
 }

 public function check_type($aTypeOfArticle){
    $this->db->where("A.type=".$aTypeOfArticle);
 }

 public function check_price($aMaxPrice){
    $this->db->where("A.price<=".$aMaxPrice);
 }

 public function get_result(){
  $query = $this->db->get();
  return $query->result();
 }

}

但是当我尝试这个时,this-&gt;db-&gt;get() 返回 false。 是否有可能完成这项工作?

【问题讨论】:

    标签: php mysql codeigniter query-builder


    【解决方案1】:

    这很可能对你更有效,

    public function query()
    {
      $this->db->select('A.id, A.title, A.price');
      $this->db->from('articles A');
    
      if( check_type($aTypeOfArticle) )
      {
        $this->db->where("A.type=".$aTypeOfArticle);
      }
    
      if( check_price($aMaxPrice) )
      {
        $this->db->where("A.price<=".$aMaxPrice);
      }
    }
    
    public function check_type($aTypeOfArticle){
      // Do processing
      return true or false;
    }
    
    public function check_price($aMaxPrice){
      // Do Processing
      return true or false;
    }
    

    在单个函数中构建查询并调用另一个函数以获得处理结果。

    【讨论】:

    • 所以不能在不同的函数中拆分查询?因为我有很多标准要检查并将它们全部放在同一个函数中会非常难看。
    • 我不知道,但这并不是说没有,我只是不知道任何方式。我想说的是,我所展示的方式就是我们在这里所做的方式。
    【解决方案2】:

    看看Method Chaining。您应该能够缓存 from() 调用的返回值(例如在对象属性中),然后使用该值链接其他方法。

    【讨论】:

      【解决方案3】:

      使用 Codeigniter 查询构建器缓存,例如 $this-&gt;db-&gt;start_cache()$this-&gt;db-&gt;stop_cache()。查看Documentation了解更多详情

      class MyCart{
          public function __construct() {
              $this->db->start_cache();
              $this->db->select('A.id, A.title, A.price');
              $this->db->from('articles A');
          }
      
          public function check_type($aTypeOfArticle){
              $this->db->where("A.type=".$aTypeOfArticle);
          }
      
          public function check_price($aMaxPrice){
              $this->db->where("A.price<=".$aMaxPrice);
          }
      
          public function get_result(){
              $this->db->stop_cache();
              $query = $this->db->get();
              return $query->result();
              $this->db->flush_cache();
          }
      
      }
      

      【讨论】:

        猜你喜欢
        • 2018-02-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-03-14
        • 2021-04-18
        • 2019-09-03
        • 1970-01-01
        • 2018-06-10
        相关资源
        最近更新 更多