【问题标题】:how to "keep" codeigniter activerecord status如何“保持”codeigniter activerecord 状态
【发布时间】:2011-11-01 17:30:01
【问题描述】:

在我的文章 CURD 列表中,我需要使用多种条件从数据库中获取文章,在获取符合条件的文章数量(无限制)后,我需要获取前 10 篇符合条件的文章(限制 10)。所以我想保持activerecord状态,如果可能的话,我不需要再写那些'where'。这是我的代码:

//select num
$this->db->select('count(*) as num')
//conditions
$this->db->where/or_where/having/order_by//many conditions...
//get num
$num = $this->db->get('articles')->first_row()->num;
//get articles
$this->db->limit(10);
$articles = $this->db->get('articles')->result();

当我完成第一个查询时,活动记录状态为空,所以第二个查询是错误的。有什么办法可以保留吗?

【问题讨论】:

    标签: php mysql codeigniter activerecord


    【解决方案1】:

    我知道这是旧的,但我也在寻找一种方法来做到这一点,最终找到了内置的解决方案:

    // Start of the query you want to re-use
    $this->db->start_cache();
    //select num
    $this->db->select('count(*) as num')
    //conditions
    $this->db->where/or_where/having/order_by//many conditions...
    // End of the query you want to re-use
    $this->db->stop_cache();
    
    //get num
    $num = $this->db->get('articles')->first_row()->num;
    //get articles
    $this->db->limit(10);
    $articles = $this->db->get('articles')->result();
    
    // Clear the saved query 
    $this->db->flush_cache();
    

    【讨论】:

      【解决方案2】:

      我相信您所采取的方法没有理由不奏效。例如获取您的代码 sn-p,整理并对其应用一些条件:

      //select num
      $this->db->select('count(*) as num');
      
      //conditions
      $this->db->where(array('title' => 'Hello world'));
      
      //get num
      $num = $this->db->get('articles')->first_row()->num;
      
      //get articles
      $this->db->limit(10);
      
      $articles = $this->db->get('articles')->result();
      
      echo "!".$num."!<br />";
      print_r($articles);
      exit();
      

      在我的测试应用程序中使用它,我收集了$num 结果,然后在$articles 中收集了一个完整的记录集。

      【讨论】:

      • 我使用 $this->db->last_query() 并看到第一个查询中有条件,但在第二个查询中没有。我认为这是因为 CI 清除了这些条件以避免模棱两可的查询。顺便说一句,我使用 CI 2.0.2
      【解决方案3】:

      你可以只使用一个简单的 if 子句

      function get_data($type) {
          //select num
          $this->db->select('count(*) as num')
          //conditions
          $this->db->where/or_where/having/order_by//many conditions...
      
          //get num
          if($type == 'count')
              return $this->db->get('articles')->first_row()->num;
      
          //get articles
          if($type == 'articles') {
              $this->db->limit(10);
              return $this->db->get('articles')->result();
          }
      }
      

      虽然我不确定是否有任何特定于 codeigniter 的东西可以简化这一点,但这应该可以。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-08-23
        • 1970-01-01
        • 1970-01-01
        • 2017-01-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多