需要复杂查询方面的帮助。服务器接收一些用于查询的参数,而不是该查询序列化为 json。我需要为每个任务添加平均评级(以便可以从 json.item[i].rating 访问该字段)并使用评级对它们进行排序。
还有一件事:有没有更好的方法来保持数据库的平均评级? 我觉得一直计算评级不是好主意。
PS:顺便说一句,开关盒为空检查更快?
//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="AppBundleEntityComment", mappedBy="quest")
*/
protected $comments;
}
class Comments{
/**
* @ORMColumn(type="integer")
* @ORMId
* @ORMGeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* @ORMColumn(type="integer")
*/
protected $rating;
/**
* @ORMManyToOne(targetEntity="AppBundleEntityQuest", inversedBy="comments")
* @ORMJoinColumn(name="quest_id", referencedColumnName="id")
*/
protected $quest;
}
最简单的方法(也是整体表现的最佳方法)是将Quest
的评级存储在任务表中,并在每次编辑/添加Comment
时刷新它。你可以为此使用教义事件。
这将解决您的两个问题,因为这样您就不必在每个请求时进行计算,并且当您请求任务表时,评级将自动选择。