【发布时间】: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