【问题标题】:Counting row totals with Codeigniter Active Record使用 Codeigniter Active Record 计算行总数
【发布时间】:2011-10-07 15:30:13
【问题描述】:

我在我的数据库中存储数量的值 (int)。我需要通过将所有行总数加在一起来计算总数。 $this->db->count_all_results() 的问题在于它返回总行数,但不计算所有存储的值。任何帮助将不胜感激。

function currentDealTotalQuantity($id)
{

    $this->db->select('quantity');

    $this->db->from('table');

    $this->db->where('id', $id);

    $total_sold = $this->db->count_all_results();

    if ($total_sold > 0)
    {
        return $total_sold;
    }

    return NULL;

}

【问题讨论】:

    标签: php mysql database codeigniter codeigniter-2


    【解决方案1】:
    function currentDealTotalQuantity($id)
    {
    
        $this->db->select_sum('quantity');
    
        $this->db->from('table');
    
        $this->db->where('id', $id);
    
        $query = $this->db->get();
    
        $total_sold = $query->row()->quantity;
    
        if ($total_sold > 0)
        {
            return $total_sold;
        }
    
        return NULL;
    
    }
    

    【讨论】:

    • 收到此错误:CI_DB_mysql_result 类的对象无法转换为 int
    • 已编辑。现在请尝试一下。
    【解决方案2】:

    我相信你想要这个人:$this->db->select_sum();

    你用它替换你的select语句,这样你就有$this->db->select_sum('quantity');这将产生查询字符串SELECT SUM(quantity) as quantity

    文档位于here

    【讨论】:

      【解决方案3】:
      function currentDealTotalQuantity($id)
      {
          $qry = $this->db->select_sum('quantity')
          ->from('table')
          ->where('id', $id)
          ->get();
      
          if ($qry->num_rows() === 0)
          {
            return FALSE;
          }
      
          return $qry->row('quantity');
      }
      

      【讨论】:

        猜你喜欢
        • 2013-05-09
        • 2014-06-26
        • 2012-06-05
        • 2013-04-11
        • 2011-10-22
        • 2014-07-21
        • 2017-06-04
        • 1970-01-01
        • 2010-11-16
        相关资源
        最近更新 更多