问题描述
在我的模型中,我有一个函数可以根据category_id获取产品数量
public function products_count($category_id,$subcategory_id = null,$brand_id = null)
{
if ($category_id) {
$this->db->where('category_id',$category_id);
}
if ($subcategory_id) {
$this->db->where('subcategory_id',$subcategory_id);
}
if ($brand_id) {
$this->db->where('brand',$brand_id);
}
$this->db->where('hide_pos !=',1);
$this->db->from('products');
return $this->db->count_all_results();
}
我收到错误消息
An uncaught Exception was encountered
Type: Error
Message: Call to a member function num_rows() on boolean
Filename: /var/www/html/projects/demo/system/database/DB_query_builder.PHP
Line Number: 1429
Backtrace:
File: /var/www/html/projects/demo/app/models/admin/Pos_model.PHP
Line: 158
Function: count_all_results
错误的问题是什么?谢谢
解决方法
为什么不使用$this->db->num_rows()
代替$this->db->count_all_results()
,结果更准确,我正在重写您的函数,请尝试此操作。
public function products_count($category_id,$subcategory_id = null,$brand_id = null)
{
$this->db->from('products');
if ($category_id) {
$this->db->where('category_id',$category_id);
}
if ($subcategory_id) {
$this->db->where('subcategory_id',$subcategory_id);
}
if ($brand_id) {
$this->db->where('brand',$brand_id);
}
$this->db->where('hide_pos !=',1);
$this->db->get();
return $this->db->num_rows();
}
如果您想使用自己的代码,只需将$this->db->from('products')
放在最前面,希望它也能正常工作。
如果我要请您使用Codeigniter 4,请确保。请在下面使用它。我认为这将帮助您解决此问题。
如果要扩展到Codeigniter核心模型,则不需要$this->db
。只是
扩展到Codeigniter核心模型,使用
public function products_count($category_id,$brand_id = null)
{
$query = $this->table('products'); // self::table('products')
if ($category_id) {
$query = $query->where('category_id',$category_id);
}
if ($subcategory_id) {
$query = $query->where('subcategory_id',$subcategory_id);
}
if ($brand_id) {
$query = $query->where('brand',$brand_id);
}
$query = $query->where('hide_pos !=',1);
return $query->countAllResults();
}
如果不扩展到Codeigniter Core模型,请使用
public function __construct()
{
$this->db = db_connect();
}
public function products_count($category_id,$brand_id = null)
{
$query = $this->db->table('products');
if ($category_id) {
$query = $query->where('category_id',1);
return $query->countAllResults();
}
如果您使用的是您所说的codeigniter 3,请使用此
public function products_count($category_id,$brand_id = null)
{
$query = $this->db->from('products');
if ($category_id) {
$query = $query->where('category_id',1);
return $query->count_all_results();
}
OR
public function products_count($category_id,1)->get();
return $query->num_row();
}
我希望这种帮助不引起我的注意