gpt4 book ai didi

zend-framework2 - Zend Framework 2 分页器 + TableGateway

转载 作者:行者123 更新时间:2023-12-03 23:37:07 32 4
gpt4 key购买 nike

如何将数据库映射器与分页器一起使用?

我在理解如何使用下面的代码实现 DbSelect 分页器时遇到了一些麻烦(现在它使用的是不适用于 ResultSet 的 Iterator 适配器)。

据我所知,它并不像我希望的那样直截了当。 DbSelect 需要一个 Zend\Db\Sql\Select 和一个适配器。适配器不是问题,可以通过以下方式检索:

$this->newsContents()->getAdapter()

但我无法在不复制查询代码的情况下从 TableGateway 中获取 Select 对象。有解决这个问题的简单方法吗?

NewsController.php

<?php

namespace News\Controller;

use Zend\Paginator\Paginator;

class NewsController extends \Application\Controller\WebsiteController
{
protected $newsTable;

protected $newsContents;

protected function newsTable()
{
return $this->getServiceLocator()->get('News\Model\NewsTable');
}

protected function newsContents()
{
return $this->getServiceLocator()->get('News\Model\NewsContentsTable');
}

protected function articleId()
{
return (int) $this->params()->fromRoute('id');
}

public function articleAction()
{
$article = $this->newsTable()->getArticle($this->articleId());
$pages = $this->newsContents()->getPages($this->articleId());

$paginator = new Paginator(new \Zend\Paginator\Adapter\Iterator($pages));
$paginator->setCurrentPageNumber($this->params()->fromRoute('page'));

return array(
'css' => 'news.css',
'article' => $article,
'paginator' => $paginator,
);
}
}

NewsContentsTable.php

<?php

namespace News\Model;

use Zend\Db\Adapter\Adapter;
use Zend\Db\ResultSet\ResultSet;
use Zend\Db\TableGateway\AbstractTableGateway;
use Zend\Db\Sql\Select;

class NewsContentsTable extends \Zend\Db\TableGateway\AbstractTableGateway
{
protected $table = 'news_contents';

public function __construct(Adapter $adapter)
{
$this->adapter = $adapter;
$this->resultSetPrototype = new ResultSet;
$this->resultSetPrototype->setArrayObjectPrototype(new NewsContents);
$this->initialize();
}

public function getPages($newsId)
{
$rowset = $this->select(function(Select $select) use ($newsId)
{
$select
->order('order ASC')
->where(array('news_id' => $newsId));
});

return $rowset;
}

}

最佳答案

从 Zend Framework 2.2 开始,它更容易(并且允许您充分享受 TableGateway 提供的优势)- 您应该使用

use Zend\Db\TableGateway\TableGateway;
use Zend\Paginator\Paginator;
use Zend\Paginator\Adapter\DbTableGateway; // !!!

 
$dbTableGatewayAdapter = new DbTableGateway($this->tableGateway);
$paginator = new Paginator($dbTableGatewayAdapter);
return $paginator;

关于zend-framework2 - Zend Framework 2 分页器 + TableGateway,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12441529/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com