我有一个文章实体。文章有财产观点。视图表看起来像
id | article_id | IP
unique(article_id,ip)
现在我执行以下操作,我在ArticleRepository中修改了findAll方法。这是正确的方式,还是我可以在文章实体中做到这一点?
请求任何帮助。
/**
* Class ArticleRepository
*
* @package FrontendBundle\Entity
*/
class ArticleRepository extends EntityRepository
{
/**
* @return array
*/
public function findAll()
{
if ($all = parent::findAll()) {
foreach ($all as $article) {
$article->setViews($this->getViews($article->getId()));
}
}
return $all;
}
/**
* Add view to article.
*
* @param int $id Article id.
* @param string $ip User clients ip
*/
public function addView($id, $ip)
{
try
{
$this->_em->getConnection()->insert('articles_views', [
'article_id' => $id,
'ip' => $ip
]);
}
catch(UniqueConstraintViolationException $e)
{
// do nothing
}
}
/**
* Return views for article.
* @param int $id
*
* @return mixed
* @throws NonUniqueResultException If the query result is not unique.
* @throws NoResultException If the query returned no result.
*/
public function getViews($id)
{
// here is custom sql query to get count rows from articles_views
}
答案 0 :(得分:1)
在Symfony 5.1中,我使用的是嵌入式存储库方法public function count(array $criteria)
。
此方法甚至允许您指定将要使用的参数。因此,如果您想在不应用参数的情况下对记录数进行计数,则只需将一个空数组传递给此方法即可。
答案 1 :(得分:0)
$qb = $this->createQueryBuilder('t');
return $qb
->select('count(t.views)')
->getQuery()
->getSingleScalarResult();