我正在使用WAMP服务器2.4。我正在尝试获取数据库中不同月份的计数,但收到此错误"在非对象 result_array(("上调用成员函数 row(("。这是我的模型类的代码
public function get_current_month()
{
$this->db->select('(COUNT(DISTINCT Month))' );
$this->db->from('site_data');
$this->db->where('year =(');
$this->db->select('MAX(year )');
$this->db->from('site_data)');
$query = $this->db->get();
return $query->result_array(); //error here
}
我相信这与代码中的子查询有关,因为当我使用它时
public function get_current_month()
{
$this->db->select('(COUNT(DISTINCT Month))' );
$this->db->from('site_data');
$this->db->where('year =2013');
//$this->db->select('MAX(year )');
//$this->db->from('site_data)');
$query = $this->db->get();
return $query->result_array();
}
它工作得很好。我正在使用编码点火器
有没有人知道这里出了什么问题。
这是我在数据库中测试的查询,它运行良好
SELECT (COUNT(DISTINCT MONTH))
FROM site_data
WHERE YEAR = (
SELECT MAX(YEAR)
FROM site_data
)
您要么需要手动将子查询制作成->where()
调用,要么使用某种第三方库。请参阅代码点火器活动记录中的子查询,该子查询处理类似问题。
我只有 CI 的过往经验,但看起来很明显,您尝试通过嵌套 db->select 等来调用子查询的方式不太正确。可能有一种方法可以构建子查询,但是...
为了简单起见,您可以尝试一下:
public function get_current_month()
{
$this->db->select('(COUNT(DISTINCT Month))' );
$this->db->from('site_data');
$this->db->where('year =( SELECT MAX(year) FROM site_data)');
$query = $this->db->get();
return $query->result_array(); //error here
}
如果它有效,为什么要让它变得更复杂?
非常感谢大家。我认为添加一个从数据库中获取 MAX(year( 然后将值传递给我的函数的函数很容易。
我是这样解决的
public function get_current_month($Year)
{
$MAXYear=$Year;
$this->db->select('(COUNT(DISTINCT Month))' );
$this->db->from('site_data');
$this->db->where('year',$MAXYear);
$query = $this->db->get();
return $query->result_array();
}
其中 year 是我从控制器传递到 get_current_month(( 的值。
它就像魅力一样工作。
非常感谢您的所有建议。