问题
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