[英]Doctrine DQL conditional query with Joins
我正在嘗試使用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)
嘗試使用給定參數的Literal表達式。 試試這個:
$conditions[] = $qb->expr()->gte('service.rating', $this->expr()->literal($rating));
而不是這個:
$conditions[] = $qb->expr()->gte('service.rating', $rating);
希望這有幫助
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.