【问题标题】:Doctrine DQL conditional query with Joins带有连接的 Doctrine DQL 条件查询
【发布时间】:2016-09-09 10:25:13
【问题描述】:

我正在尝试使用 Doctrine 的查询构建器构建动态查询。我有可选参数。我如何有条件地将它添加到语句中?我也有关联(例如,Service 与Category 具有多对一关系)

 $qb = $this->createQueryBuilder('service');
 $qb->join('service.category', 'category');

 $conditions = array();

 if ($categoryId != null) {

        $category = $this->getEntityManager()
            ->getRepository('AppBundle:Category')->find($categoryId);

        if($category == null){
            throw new ApiException('category not found');
        }

        $conditions[] = $qb->expr()->like('category.path', $category->getPath().'%');
    }

 if ($userId != null) {
        $user = $this->getEntityManager()->getRepository('AppBundle:User')->find($userId);
        if($user == null){
            throw new ApiException('user not found');
        }

        $conditions[] = $qb->expr()->eq('service.user', $userId);
    }

  if ($rating != null) {
        $conditions[] = $qb->expr()->gte('service.rating', $rating);
    }

 $conditions = call_user_func_array(array($qb->expr(), 'andX'), $conditions);

 $qb->where($conditions);

 $qb->addOrderBy('service.created', 'DESC');

 return $qb;
}

当我尝试发送查询时

http://127.0.0.1:8000/api/services?limit=10&categoryId=45

我收到以下错误:

Error: Expected StateFieldPathExpression | string | InputParameter | FunctionsReturningStrings | AggregateExpression, got "45" (500 Internal Server Error)

【问题讨论】:

  • 错误看起来与$categoryId = 45有关,但不清楚,$category->getPath() 的值是多少?

标签: php mysql symfony doctrine-orm dql


【解决方案1】:

尝试使用给定参数的 Literal 表达式。所以试试这个:

$conditions[] = $qb->expr()->gte('service.rating', $this->expr()->literal($rating));

而不是这个:

$conditions[] = $qb->expr()->gte('service.rating', $rating);

希望有帮助

【讨论】:

  • $rating 是数字吗?为什么需要这样做service.rating > '1'?
猜你喜欢
  • 2012-02-25
  • 1970-01-01
  • 1970-01-01
  • 2012-01-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-04-23
  • 1970-01-01
相关资源
最近更新 更多