Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom Query Pagination Cakephp

I have a custom query in my controller and I would like to implement the custom query pagination I found on cakephp.org but their example is not similar to mine. Can someone please help me paginate this result in my view:

    $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);
like image 885
Hooman Ahmadi Avatar asked Mar 14 '26 19:03

Hooman Ahmadi


2 Answers

Implement paginate and paginateCount in your model:

function paginate($conditions, $fields, $order, $limit, $page, $recursive, $extra)
{
    return $this->query('SELECT ...');
}

function paginateCount($conditions, $recursive, $extra)
{
    return $this->query('SELECT COUNT(.....');
}

Also check out the paginate function in: cake/libs/controller/controller.php

like image 172
GJ. Avatar answered Mar 17 '26 09:03

GJ.


This looks like it should be able to be done without resorting to using custom pagination.

You should set in the following relationships in your models:

Car hasMany (or hasOne) CarImage
CarImage belongsTo Car

Then you should be able to get this exact data using the following:

<?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);
  }
}
?>

For more information on complex find conditions (which can be applied to paginate by passing in an array like I did in the above example): http://book.cakephp.org/view/74/Complex-Find-Conditions

like image 43
spelley Avatar answered Mar 17 '26 08:03

spelley



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!