I have an article entity. Article has property views. Views table looks like
id | article_id | ip
unique(article_id, ip)
Now I do the following, i modify findAll method in ArticleRepository. Is it a right way or i can do it in article entity?
Thx for any help.
/**
* 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
}