4

您好,我有以下代码,

$this->load->library('pagination');
$this->data['products'] = $this->products_model->get_products_and_category($this->uri->segment(4));

$config['base_url'] = base_url()."admin/products/manage/";
$config['total_rows'] = $this->db->get('products')->num_rows();
$config['per_page'] = 20;
$config['full_tag_open'] = '<div class="btn-group">';
$config['full_tag_close'] = '</div>';
$config['anchor_class'] = 'class="btn" ';
$config['cur_tag_open'] = '<div class="btn">';
$config['cur_tag_close'] = '</div>';
$config['uri_segment'] = 4;

$this->pagination->initialize($config); 
$this->data['pagination'] = $this->pagination->create_links();

$this->template->build('admin/products/index', $this->data);

正在运行的查询get_products_and_category($this->uri->segment(4))如下所示,

public function get_products_and_category($offset=0) {
    $this->db->select('products.product_id, products.product_title, products.product_created, products.parent_category, categories.category_id, categories.category_title')
    ->from('products')
    ->join('categories' , 'products.parent_category = categories.category_id', 'left')
    ->order_by('products.product_title', 'ASC')
    ->limit(25, $offset);

    $query = $this->db->get();
    return $query->result_array();
}

我的表中有 25 个结果,我想每页显示 20 个,所以根据我的数学计算,分页类应该创建 2 个链接(第 1 页和第 2 页),第一页应该有 20 个结果,第二个应该有 4结果,但是我根本没有得到任何链接,我做错了吗?

4

2 回答 2

4

LIMIT 子句可用于限制 SELECT 语句返回的行数。

现在您有 25 个结果,并且您将查询限制为返回 25 个结果,因此您的分页可能无法正常工作。

尝试在查询中传递 $config[per_page]

$this->data['products'] = $this->products_model->get_products_and_category($config['per_page'],$this->uri->segment(4));

然后在查询中(注意我们将 per_page 变量传递给 limit())

public function get_products_and_category($num, $offset=0) {
$this->db->select('products.product_id, products.product_title, products.product_created, products.parent_category, categories.category_id, categories.category_title')
->from('products')
->join('categories' , 'products.parent_category = categories.category_id', 'left')
->order_by('products.product_title', 'ASC')
->limit($num, $offset); // Here we pass the per_page var

$query = $this->db->get();
return $query->result_array();
}

希望这可以帮助

于 2012-05-04T16:44:08.040 回答
0

Altrim 的回答非常好。但为了符合 CodeIgniter,我建议改用它:

public function get_products_and_category($offset=0) {
    $this->db->select('products.product_id, products.product_title, products.product_created, products.parent_category, categories.category_id, categories.category_title')
    ->from('products')
    ->join('categories' , 'products.parent_category = categories.category_id', 'left')
    ->order_by('products.product_title', 'ASC')
    ->limit($this->per_page, $offset); // Here we pass the per_page var

    $query = $this->db->get();
    return $query->result_array();
}

您已经在中定义 per_page$config['per_page'] = 20;

由于在函数中$this->pagination->initialize($config);转换。$key (per_page) => $value (20)$this->$key = $valueinitialize

于 2012-05-04T16:48:22.847 回答