我正在尝试将opencart地址列表分解为每页20个,但仍显示第1页和第2页的所有列表.请看一下代码,我必须做错什么.
分页看起来很好
1 2 > >|
Showing 1 to 20 of 31 (2 Pages)
受保护函数getList()中的控制器帐户address.php页面上的代码(我也尝试了公共函数index()).
if (isset($this->request->get['page'])) {
$page = $this->request->get['page'];
} else {
$page = 1;
}
$data = array(
'start' => ($page - 1) * 20,
'limit' => 20
);
$address_total = $this->model_account_address->getTotalAddresses($data);
$results = $this->model_account_address->getAddresses();
$pagination = new Pagination();
$pagination->total = $address_total;
$pagination->page = $page;
$pagination->limit = 20;
$pagination->text = $this->language->get('text_pagination');
$pagination->url = $this->url->link('account/address', 'page={page}', 'SSL');
$this->data['pagination'] = $pagination->render();
和模型帐户address.php上的代码
public function getDetails($data = array()) {
$sql = $this->db->query("SELECT * FROM `" . DB_PREFIX . "address` WHERE customer_id = '" . (int)$this->customer->getId() . "'");
if (isset($data['start']) || isset($data['limit'])) {
if ($data['start'] < 0) {
$data['start'] = 0;
}
if ($data['limit'] < 1) {
$data['limit'] = 20;
}
$sql .= " LIMIT " . (int)$data['start'] . "," . (int)$data['limit'];
}
$query = $this->db->query($sql);
$details = $query->rows;
return $details;
}
这是在视图address_list.tpl上
<?php echo $pagination; ?>
请指教.
解决方法:
问题出在您的模型中.您在填写LIMIT和OFFSET之前运行查询,将模型更改为此:
public function getDetails($data = array()) {
$sql = 'SELECT * FROM `' . DB_PREFIX . 'address` WHERE customer_id = ' . (int)$this->customer->getId();
if (isset($data['start']) || isset($data['limit'])) {
if ($data['start'] < 0) {
$data['start'] = 0;
}
if ($data['limit'] < 1) {
$data['limit'] = 20;
}
$sql .= ' LIMIT ' . (int)$data['start'] . ',' . (int)$data['limit'];
}
$query = $this->db->query($sql);
return $query->rows;
}
这应该做.
实际上,在您第一次调用$sql = $this-> db-> query(“ …”);之后, (模型方法的第一行)$sql变量不包含SQL查询,而是包含属性行(第一行),行(所有检索到的行)和num_rows(检索到的行数)的OpenCart DB资源对象.因此,您的第二个调用$query = $this-> db-> query($sql);应该会给您一个错误-如果未显示该错误,则可能是您隐藏了PHP错误.检查您的PHP错误日志(或OpenCart的错误日志)以找出答案.
编辑:
然后,在您的控制器中,您将遇到此逻辑错误:您正在为getTotalAddresses($data)设置LIMIT和OFFSET,这应该计算所有地址-但这将始终返回数字20.另一方面,应该返回的方法获取这些参数,但不获取它们:getAddresses();
因此,请修复您的控制器以执行此操作:
$address_total = $this->model_account_address->getTotalAddresses();
// no $data here as we want all the addresses to be counted ----^^
$results = $this->model_account_address->getAddresses($data);
// we pass $data here so the LIMIT is applied --------^^^^^
还有一件事:在控制器中调用getAddresses,但在模型中定义了getDetails …是否确定不想将getDetails重命名为getAddresses?