How to update the view counter in symfony and doct

2019-07-22 12:26发布

问题:

/**
     * Lists all user entities.
     *
     * @Route("/article/{id}/{title}", name="article")
     * @Template()
     */
    public function articleAction($id, $title) {
        $em = $this->getDoctrine()->getManager();
        $article = $em->getRepository('TryoneeArticleBundle:Article')->find($id);
        if (!$article)
            return $this->redirect($this->generateUrl('main'));

        if ($article->getTitle() != str_replace('-', ' ', $title)) {
            return $this->redirect($this->generateUrl('article', array('id' => $article->getId(), 'title' => str_replace(' ', '-', $article->getTitle()))));
        }
        $keywordarray = explode(',', $article->getKeyword());

        $newview = $article->getTotalView() + 1;
        $article->setTotalView($newview);
        $em->persist($article);
        $em->flush();

        return array(
            'article' => $article,
            'id' => $id,
            'keywords' => $keywordarray,
            'view' => $newview
        );
    }

This is my controller code in which i want to get the article form the database and increment the view. But this code is showing a strange behavior some time it increments 4 time and 2 time and single time.

Am i missing something....? Any help is appreciated