K
K
KOS_MOS2013-10-01 18:41:24
symfony
KOS_MOS, 2013-10-01 18:41:24

Checking for the existence of a many-to-many relationship in Doctrine?

I have an Article class:

/**<br>
 * @ORM\ManyToMany(targetEntity="Acme\UserBundle\Entity\User", inversedBy="like_articles")<br>
 */<br>
protected $like_users;<br>

and the User class:
/**<br>
 * @ORM\ManyToMany(targetEntity="Acme\BlogBundle\Entity\Article", mappedBy="like_users")<br>
 */<br>
protected $like_articles;<br>

An established link indicates that the user has marked the article as liked.
And of course, the user can mark one article once, in order to check it, I do this:
$article = $em->find('AcmeBlogBundle:Article', $article_id);<br><br>
if($article->getLikeUsers()->contains($this->getUser()))<br>
{<br>
    throw new BadRequestHttpException('Relationship exist');<br>
}<br><br>

I turn on the query log in mysql and see that the following query is generated to check contains:
SELECT <br>
  t0.username AS username1,<br>
  ...<br>
FROM<br>
  user t0 <br>
  INNER JOIN article_user <br>
    ON t0.id = article_user.user_id <br>
WHERE article_user.article_id = '6252';<br>

It would be logical if the query also included:
AND t0.id = <id пользователя><br>
That is, it turns out that if 10,000 people vote for an article, then to check whether 10,001 users voted, 10,000 records will be extracted?
I'm new to Symfony, can you tell me what's wrong?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
N
Nikita Gusakov, 2013-10-02
@hell0w0rd

It would be logical if the request also included:

Not logical. join covers this condition with his head

S
stnw, 2013-10-02
@stnw

Because you check with the user later in PHP, and not in the request itself. Should be something like this:

$count = $this->entityManager->getRepository('AcmeBlogBundle:Article')->createQueryBuilder('a')
             ->select('COUNT(a)')
            ->join('a.like_users', 'u')
            ->where('a.id = :article_id')
            ->setParameter("article_id", $article_id)
            ->andWhere('u.id = :user_id')
            ->setParameter("user_id", $this->getUser()->getId())
           ->getQuery()
            ->getSingleScalarResult();

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question