我正在尝试使用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)
答案 0 :(得分:0)
尝试使用给定参数的Literal表达式。所以试试这个:
$conditions[] = $qb->expr()->gte('service.rating', $this->expr()->literal($rating));
而不是:
$conditions[] = $qb->expr()->gte('service.rating', $rating);
希望这个帮助