- $sql = 'DELETE et FROM entry_tag et WHERE et.entry_id IN ( SELECT e.id FROM entry e WHERE e.user_id = :userId ) AND et.tag_id = :tagId';
- $stmt = $this->getEntityManager()->getConnection()->prepare($sql);
- $stmt->execute([
- 'userId' => $userId,
- 'tagId' => $tag->getId(),
- ]);
+ $entries = $this->getBuilderByUser($userId)
+ ->innerJoin('e.tags', 't')
+ ->andWhere('t.id = :tagId')->setParameter('tagId', $tag->getId())
+ ->getQuery()
+ ->getResult();
+
+ foreach ($entries as $entry) {
+ $entry->removeTag($tag);
+ }
+
+ $this->getEntityManager()->flush();
+
+ // An other solution can be to use raw query but I can't find a way to retrieve the `entry_tag` table name since it can be prefixed....
+ // $sql = 'DELETE et FROM entry_tag et WHERE et.entry_id IN ( SELECT e.id FROM entry e WHERE e.user_id = :userId ) AND et.tag_id = :tagId';
+ // $stmt = $this->getEntityManager()->getConnection()->prepare($sql);
+ // $stmt->execute([
+ // 'userId' => $userId,
+ // 'tagId' => $tag->getId(),
+ // ]);
+ }
+
+ /**
+ * Find all entries that are attached to a give tag id.
+ *
+ * @param int $userId
+ * @param int $tagId
+ *
+ * @return array
+ */
+ public function findAllByTagId($userId, $tagId)
+ {
+ return $this->getBuilderByUser($userId)
+ ->innerJoin('e.tags', 't')
+ ->andWhere('t.id = :tagId')->setParameter('tagId', $tagId)
+ ->getQuery()
+ ->getResult();