我正在使用CakePHP 2开发图库软件,在尝试分页内容时遇到了一个问题。
我有两个主要的模型在网站上,他们是Album和Image。它们是由一个有很多关系的相册连接的,其中一个相册可以有很多图像,每个图像属于一个相册。我可以使用AlbumsController.php文件中的以下内容对相册列表进行分页,不存在任何问题:
public $paginate = array(
'limit' => 21
);然后,在我想要分页的方法中(例如,index):
public function index() {
$this->set('albums', $this->paginate());
}我在对专辑视图进行分页时遇到了问题。对于相册视图,系统使用以下函数使用关系获取属于该相册的所有图像:
public function view($id = null) {
if (!$id) {
throw new NotFoundException(__('Album not found.'));
}
$album = $this->Album->findById($id);
if (!$album) {
throw new NotFoundException(__('Album not found.'));
}
$this->set('album', $album);
}但是,我不知道如何使系统根据图像分页相册视图。我试过使用:
$this->set('albums', $this->paginate());徒劳无功(系统似乎忽略了它),同时也尝试重载paginate()函数,而只得到错误。有人能为我指出正确的方向吗?这是一个非常简单的关系,我相信答案可能也很简单,但我似乎找不到它,甚至在Stack溢出中,我发现的大多数相关线程都是关于更复杂的系统的,在关系中进行搜索。我不需要这些,这是一个非常简单的分页案件。
发布于 2014-01-10 22:02:51
我终于搞定了。下面是这个函数的最终结果:
public function view($id = null){
if (!$id) {
throw new NotFoundException(__('Album not found.'));
}
$album = $this->Album->findById($id);
if (!$album) {
throw new NotFoundException(__('Album not found.'));
}
$this->paginate = array(
'conditions'=>array(
'Image.album_id'=>$id),
'limit' =>'21'
);
$album = $this->paginate('Image');
$this->set('album', $album);
$this -> set('id', $id);
}因此,我所做的就是为分页数组添加一组新的约束,然后强制它根据相册ID对图像进行分页。这也有迫使我重写专辑view.ctp文件的附带作用,因为它完全改变了模板接收数据的方式。在这种情况下,我不得不停止使用foreach($album['Image'] as $image)来查看图像,而是使用while($image_no < 21)循环来访问$album[number]['Image']的每个实例。
我相信一定会有更好/更优雅的方法来达到我所需要的,但是由于我找不到其他的方法,所以我会把它留在这里记录在案,以防其他人遇到同样的问题。
发布于 2014-01-08 19:48:25
也许它会对你有帮助:
class AlbumsController extends AppController {
var $name = 'Albums';
var $paginate = array(
'limit' => 95,
'order' => array(
'Album.name' => 'asc')
);
function index() {
$this->Album->recursive = 0;
$this->set('albums', $this->paginate());
$this->set("title_for_layout","CakeGal");
}
function view($id = null) {
if (!$id) {
$this->Session->setFlash(__('Invalid album', true));
$this->redirect(array('action' => 'index'));
}
$this->set('album', $this->Album->read(null, $id));
$this->set("title_for_layout", $this->Album->data['Album']['name']);
}}
https://stackoverflow.com/questions/21005024
复制相似问题