/** * Save Tag Relation and add create and save tags if don't exist * @param Taggable $model */ public function saveRelation(Taggable $model) { if (!$model->getRemove()) { if ($model->getTags()->count() > 0) { $addedTags = $model->getTags(); $model_id = $model->getModelId(); $model_name = $model->getModel(); $addNewTags = $addedTags; $tagsRelationExisted = $this->findRelationByTagName($model->getTags(), $model); //Remove existed Tag from collection foreach ($tagsRelationExisted as $tagExisted) { if ($addedTags->exists(function ($index, Tag $addedTag) use($tagExisted) { return $addedTag->getName() === $tagExisted->getName(); })) { $addNewTags->removeElement($tagExisted); } } //Save foreach ($addNewTags as $tag) { $relation = new TagRelation(); $relation->setModel($model_name); $relation->setModelId($model_id); $relation->setTag($tag); $this->em->persist($relation); } if (count($addNewTags) > 0) { $this->em->flush(); } } } }
protected function findRelationByTagName(ArrayCollection $names, Taggable $model) { $slugified = []; foreach ($names as $name) { $slugified[] = $name->getSlug(); } $query = $this->em->createQueryBuilder()->select('t')->from($this->tag, 't')->innerJoin('t.tagRelation', 'tg', Expr\Join::WITH, 'tg.model = :model AND tg.modelId = :modelId')->addSelect('tg')->where($this->em->createQueryBuilder()->expr()->in('t.slug', $slugified))->setParameter('model', $model->getModel())->setParameter('modelId', $model->getModelId())->getQuery()->getResult(); return $query; }