Propel Save Object Error Tags

♀尐吖头ヾ 提交于 2019-12-25 02:34:35

问题


I have problem with my little part of code. Symfony2, PROPEL ORM.

    $tagNames = $tags->getTags();
    $tagsArray = explode(',', $tagNames);

    $postTagToDelete = PostTagQuery::create()->filterByPostId($post->getId())->find();
    if ($postTagToDelete) {
        $postTagToDelete->delete();
    }

    foreach ($tagsArray as $tagName) {
        $tag = TagQuery::create()->filterByName($tagName)->findOne();
        //when i find an existing tag,
        // there is no need to create another one
        //I just simply add it **(it's not working here)**
        if ($tag != null) {
            $post->addTag($tag);

        } else {
            //when tag is new
            $tag = new Tag();
            $tag->setName($tagName);


            $post->addTag($tag);

        }
    }

Everytime I'm creating new objects of PostTags. I clean the main object of PostTag and then create a new ones.

Problem is that, it always does not saving the first tag I have in my $tagNames.

To be more specific, let's pretend that I have four elements in $tagsArray.

[first, second, third, fourth]

Every of them IS the database already, so it gonna enter first if four times.

The problem is that only second, third and fourth will be saved. There will be no first . Why?

Another example is that if I have array[first] and do the same (first is in the databse already) it will be saved every only the second time. So I have sth like is in database, database empty, is in database, database empty,[...] every request attempt.

Any suggestions?

Thank you, I really need that.

Thx, D

After all I found solution which works like a charm.

    $tagNames = $tags->getTags();
    $tagsArray = explode(',', $tagNames);
    $tagsArray = array_unique($tagsArray);

    $tagManager = $this->container->get('back_tag.manager');
    $tags = new PropelOwnCollection();
    foreach ($tagsArray as $tag) {
        if (is_numeric($tag)) { //naprawa bledu pluginu select2
            $tags->append($tagManager->findOneOrCreateById($tag));
        } else if (!empty($tag)) {
            $tags->append($tagManager->findOneOrCreateByName($tag));
        }
    }
    $post->setTags($tags);
    $post->save();

来源:https://stackoverflow.com/questions/23376335/propel-save-object-error-tags

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!