返回首页 - Notes - 2015

Symfony2 中使用分页


方法一

这种方法的查询条件不支持 LIKE 匹配,so,基本没什么用。代码如下:

<?php

$req = $this->getRequest();
$ename = trim($req->get('ename'));
$name = trim($req->get('name'));
$status = intval($req->get('status', 0));
$page = intval($req->get('page', 1));  // 页码
$page_size = intval($req->get('page_size', 30));  // 分页大小

$where = [];
if ($ename) {
    $where['ename'] = $ename;
}
if ($name) {
    $where['name'] = $name;
}
if ($status) {
    $where['status'] = $status;
}
$em = $this->getDoctrine()->getManager();
$groups = $em->getRepository('SiteAdminBundle:Groups')->findBy($where, ['id' => 'desc'], $page_size, $page_size * ($page - 1));
$groupsCount = $em->getRepository('SiteAdminBundle:Groups')->findBy($where);
$count = count($groupsCount);

方法二

想分页,又想用 LIKE,那就像下面这么做吧:

<?php

use Doctrine\ORM\Tools\Pagination\Paginator;

/**
 * 根据条件获取分页数据.
 */
protected function getPaginatorDataByCondition($dql, $count = false, $page = 1, $page_size = 30)
{
    $em = $this->getEmInstance();
    $query = $em->createQuery($dql)
        ->setFirstResult($page_size * ($page - 1))
        ->setMaxResults($page_size);

    $paginator = new Paginator($query, true);

    if ($count) {  // 获取总数
        return count($paginator);
    }

    return $paginator;
}



$username = trim($this->getRequestItem('username'));
$nickname = trim($this->getRequestItem('nickname'));
$group_ename = trim($this->getRequestItem('group_ename'));
$status = intval($this->getRequestItem('status', 0));
$sdate = trim($this->getRequestItem('sdate'));
$edate = trim($this->getRequestItem('edate'));
$page = intval($this->getRequestItem('page', 1));
$page_size = intval($this->getRequestItem('page_size', 30));

$dql = 'SELECT a FROM SiteCommonBundle:Admins a WHERE 1=1';
if ($username) {
    $dql .= " AND a.username LIKE '%{$username}%'";
}
if ($nickname) {
    $dql .= " AND a.nickname LIKE '%{$nickname}%'";
}
if ($group_ename) {
    $dql .= " AND a.groupEname = '{$group_ename}'";
}
if ($status) {
    $dql .= " AND a.status = {$status}";
}
if ($sdate) {
    $dql .= " AND a.ctime >= '{$sdate}'";
}
if ($edate) {
    $dql .= " AND a.ctime <= '{$edate} 23:59:59'";
}
$dql .= ' ORDER BY a.id DESC';
$admins = $this->getPaginatorDataByCondition($dql, false, $page, $page_size);
$count = count($admins);

注意,上述代码直接这么写肯定是报错的了,因为我为了方便演示,把外面的类啊、辅助方法啊都省略了,能看明白代码是什么意思就行


date:2015-07-02、2015-07-03