2016-07-28 3 views
0

私は記事エンティティを持っています。記事にはプロパティビューがあります。ビューの表は次のようになりますSymfony。エンティティIDのエンティティプロパティの行数をカウントする

id |記事ID | IP

ユニーク(article_idに、IP)

今、私は次の操作を行い、私はArticleRepositoryでfindAllメソッドを変更します。それは正しい方法ですか、私は記事の実体でそれを行うことができますか?

任意のヘルプについてはThxをご覧ください。

/** 
* 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
$qb = $this->createQueryBuilder('t'); 
return $qb 
    ->select('count(t.views)') 
    ->getQuery() 
    ->getSingleScalarResult(); 
+0

あなたは私を理解しません。 articles_viewsにはエンティティがないため、querybuilderは機能しません。 – Tapakan

+0

質問をする方法を知っています。私はこれが正しい方法/ symfonyの方法であることを知りたいですか?たぶん良い方法がありますか? – Tapakan

関連する問題