需要有关复杂查询的帮助。 服务器接收一些用于查询的参数,而该查询正在序列化为json。我需要为每个任务添加平均等级(因此可以从json.item [i] .rating访问该字段)并对其进行排序。
还有一件事:是否有更好的方法来保持db的平均评级?我觉得一直计算评分并不是一个好主意。
PS:对于空检查,btw switch case更快?
//some params
$repository = $this->getDoctrine()->getRepository('AppBundle:Quest');
$qb = $repository->createQueryBuilder('q')
->innerJoin('q.city', 'c')
->where('c.id = :city_id')
->setParameter('city_id', $cityId);
if($minPlayers != null){
$qb ->andWhere('q.minplayers >= :minplayers')
->setParameter('minplayers', $minPlayers);
}
if($maxPlayers != null){
$qb ->andWhere('q.maxplayers <= :maxplayers')
->setParameter('maxplayers', $maxPlayers);
}
if($tagsId != null){
$qb ->innerJoin('q.tags','t')
->andWhere('t.id IN (:tags)')
->setParameter(':tags', implode(",", $tagsId));
}
if($organizerId != null){
$qb ->andWhere('q.organizer = :organizer_id')
->setParameter('organizer_id', $organizerId);
}
if($ispremium != null){
$qb ->andWhere('q.ispremium = :isPremium')
->setParameter('isPremium', $ispremium)
->addOrderBy('q.premiumorder', 'ASC');
}
$qb ->setFirstResult($FirstResult)
->setMaxResults($MaxResults);
$query = $qb->getQuery();
$paginator = new Paginator($query, $fetchJoinCollection = true);
$c = count($paginator);
$result = $query->getResult();
$serializer = $this->get('jms_serializer');
$data = $serializer->serialize($result, 'json',
SerializationContext::create()
->enableMaxDepthChecks()
->setGroups(array('questSearch'))
);
$json ='{"total_count":'.$c.',"items":'.$data.',"amountOfelems":'.$amountOfelems.',"citySlug":'.json_encode($citySlug).',"userId":'.json_encode($userId).'}';
return new JsonResponse($json);
实体:
class Quest{
...
/**
* @OneToMany(targetEntity="AppBundle\Entity\Comment", mappedBy="quest")
*/
protected $comments;
}
class Comments{
/**
* @ORM\Column(type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* @ORM\Column(type="integer")
*/
protected $rating;
/**
* @ORM\ManyToOne(targetEntity="AppBundle\Entity\Quest", inversedBy="comments")
* @ORM\JoinColumn(name="quest_id", referencedColumnName="id")
*/
protected $quest;
}
答案 0 :(得分:1)
最简单的方法(也是整体表现的最佳方式)是将Quest
的评分存储在任务表中,并在每次编辑/添加Comment
时刷新它。你可以使用Doctrine Events。
这可以解决您的问题,因为这样您就不必在每个请求中计算,并且当您要求任务表时,评级将自动被选中。