0
我建立一個自定義查詢,並試圖使用默認的分頁程序,就像這樣:CakePHP的自定義查詢分頁程序:自定義功能PAGINATE不叫
WodsController.php
$userId = $this->Auth->user('id');
$connection = ConnectionManager::get('default');
$result = $connection->execute("SELECT wods.id, wods.titulo , wods.dia , wods.tempo, wods.repeticoes ,userwods.user_id FROM wods
LEFT JOIN userwods ON userwods.wod_id = wods.id WHERE userwods.user_id is null or userwods.user_id=4 order by wods.dia desc limit 50")->fetchAll('assoc');
$results = array();
foreach ($result as $r) {
$entity = $this->Wods->newEntity($r);
array_push($results, $entity);
}
$wods = $this->paginate($results);
$this->set('_serialize', ['wods']);
我得到這個錯誤「無法找到與paginate兼容的對象「。
現在我是tryng實現自定義查詢分頁器,但它不工作。 我在模型中實現了paginate和paginateCount函數。 Wods.php文件:
public function paginate($conditions, $fields, $order, $limit, $page = 1, $recursive = null, $extra = array()) {
$recursive = -1;
$this->useTable = false;
$sql = '';
$sql .= "SELECT wods.id, wods.titulo , wods.dia , wods.tempo, wods.repeticoes ,userwods.user_id FROM wods LEFT JOIN userwods ON userwods.wod_id = wods.id WHERE userwods.user_id is null or userwods.user_id=4 order by wods.dia desc limit ";
// Adding LIMIT Clause
$sql .= (($page - 1) * $limit) . ', ' . $limit;
$results = $this->query($sql);
return $results;
}
public function paginateCount($conditions = null, $recursive = 0, $extra = array()) {
$sql = '';
$sql .= "SELECT wods.id, wods.titulo , wods.dia , wods.tempo, wods.repeticoes ,userwods.user_id FROM wods LEFT JOIN userwods ON userwods.wod_id = wods.id WHERE userwods.user_id is null or userwods.user_id=4 order by wods.dia desc";
$this->recursive = $recursive;
$results = $this->query($sql);
return count($results);
}
在控制器WodsController.php
public function index()
{
$this->Wods->recursive = 0;
$this->paginate = array('Wods'=>array('limit'=>10));
$this->set('wods', $this->paginate('Wods'));
}
但自定義分頁程序不叫,繼續調用默認PAGINATE功能。爲什麼?
你只是想每頁行數更改爲10?如果是這樣,你可以使用默認的paginate函數,並使用'$ this-> paginate = array('limit'=> 10);'用'$ this-> paginate();' – dragmosh
我的問題當我有自定義查詢時,默認分頁程序會使其工作。我嘗試過,並且收到了這個問題:「無法找到與paginate兼容的對象」 –
看起來您正嘗試使用自定義分頁來繞過CakePHP ORM。我建議反對。您可以使用CakePHP的ORM編寫大多數自定義查詢(包括連接,組,子查詢和按參數排序),並設置分頁程序來運行該查詢。 – dragmosh