当我使用分页

时间:2017-03-25 13:59:56

标签: mysql symfony doctrine-orm doctrine symfony-2.8

如果我使用getLatestProducts()课程中的ProductRepository函数,则会出错:

An exception occurred while executing 'SELECT DISTINCT id_0 FROM (
    SELECT p0_.id AS id_0, p0_.title AS title_1, p0_.type AS type_2, p0_.status AS status_3, p0_.price AS price_4, p0_.price_sale AS price_sale_5, p0_.created AS created_6, p0_.updated AS updated_7, p0_.number_orders AS number_orders_8, p0_.quantity AS quantity_9, p0_.image_name AS image_name_10, p0_.serial AS serial_11
    FROM product p0_) dctrn_result
    ORDER BY type_2 DESC LIMIT 10 OFFSET 0':

SQLSTATE[HY000]: General error:
    3065 Expression #1 of ORDER BY clause is not in SELECT list,
    references column 'dctrn_result.type_2' which is not in SELECT list;
    this is incompatible with DISTINCT

如果我从->orderBy('p.type', 'DESC')函数中删除字符串getLatestProducts,则分页有效!我做错了什么?

public function getLatestProducts($currentPage = 1, $limit = 5)
{
    $qb = $this->createQueryBuilder('p')
        ->orderBy('p.type', 'DESC')
        ->getQuery();

    $paginator = $this->paginate($qb, $currentPage, $limit);

    return $paginator;

}

public function paginate($dql, $page = 1, $limit = 5)
{
    $paginator = new Paginator($dql);

    $paginator->getQuery()
        ->setFirstResult($limit * ($page - 1)) // Offset
        ->setMaxResults($limit); // Limit

    return $paginator;
}

我知道,我可以使用KnpPaginatorBundle,但我想修复此问题。如果我在where函数中添加一些getLatestProducts参数进行查询,那么它就可以了......

1 个答案:

答案 0 :(得分:0)

正如常规错误建议的那样,请尝试添加到createQueryBuilder()

->select('p.id, p.type')