我的控制器中有一个自定义查询,我想实现我在cakephp.org上找到的自定义查询分页,但它们的示例与我的不同。有人可以帮助我在我的观点中对此结果进行分页:
$cars = $this->Car->query(" select Car.id, Car.make, Car.model, Car.year, Car.description, CarImage.thumbnail
from cars Car
inner join car_images CarImage on Car.default_image_id = CarImage.id
where Car.make like '" . $category . "'
order by Car.created DESC
limit 10");
$this->set('cars', $cars);
答案 0 :(得分:4)
在您的模型中实施paginate和paginateCount:
function paginate($conditions, $fields, $order, $limit, $page, $recursive, $extra)
{
return $this->query('SELECT ...');
}
function paginateCount($conditions, $recursive, $extra)
{
return $this->query('SELECT COUNT(.....');
}
另请查看以下内容中的paginate函数:cake / libs / controller / controller.php
答案 1 :(得分:2)
看起来应该可以在不使用自定义分页的情况下完成。
您应该在模型中设置以下关系:
Car hasMany(或hasOne)CarImage
CarImage属于Car
然后您应该能够使用以下内容获得这些确切的数据:
<?php
class CarsController extends AppController {
var $paginate = array('limit'=>'10',
'order'=>'Car.created',
'fields'=>array('Car.model','Car.year','Car.description',
'CarImage.thumbnail'));
function test() {
// not sure where you are getting the where clause, if its from some form
// you'll want to check look in $this->data
$category = "somevalue";
// set the LIKE condition
$conditions = array('Car.make LIKE' => '%'.$category.'%');
// apply the custom conditions to the pagination
$this->set('cars', $this->paginate($conditions);
}
}
?>
有关复杂查找条件的更多信息(可以像我在上面的示例中那样通过传入数组应用于分页):http://book.cakephp.org/view/74/Complex-Find-Conditions
答案 2 :(得分:1)
在Cake 3中,您可以使用带有函数find()的deafult paginator。
按照示例:
$query = $this->Car->find()
->select(['Car.id', 'Car.make','Car.model','Car.year','Car.description','CarImage.thumbnail'])
->join([
'table' => 'CarImage',
'alias' => 'CarImage',
'type' => 'INNER',
'conditions' => 'CarImage.id = Car.default_image_id,
])
->where(['Car.make LIKE' => '%$category%'])
->order(['Car.created' => 'DESC'])
->limit(50)
$cars = $this->paginate($query);
$this->set(compact('cars'));
$this->set('_serialize', ['cars']);
答案 3 :(得分:0)
mysql限制子句支持卷和偏移量,因此每页10个结果....
select * from table limit 0, 10
第1页
select * from table limit 10, 10
第2页
select * from table limit 20, 10
第3页
select * from table limit ($page-1)*$perPage, $perPage
通用
答案 4 :(得分:0)
mysql限制子句支持卷和偏移量,因此每页10个结果....