2
votes

I have an Item object which has a 1:n relation to categories. My Item Model contains:

setCategories(\TYPO3\CMS\Extbase\Persistence\ObjectStorage $categories)
getCategories()
addCategory(VENDX\Items\Domain\Model\Category $category)
removeCategory(VENDX\Items\Domain\Model\Category $category)

but I am not able to add multiple categories to an itemobject. i tried:

$category = $this->objectManager->get('VENDX\Items\Domain\Model\Category');

$category->setCatName('Cat1');  //First category
$item->addCatgeory($category);

$category->setCatName('Cat2'); //Second category
$item->addCategory($category);

after adding $item to my $itemrepository it just saves the last category "Cat2" into the db. What am i missing??

also tried that:

$categories = $this->objectManager->get('TYPO3\CMS\Extbase\Persistence\ObjectStorage');
$category = $this->objectManager->get('VENDX\Items\Domain\Model\Category');
$category->setCatName('Cat1');  //First category
$categories->attach($category);

$category->setCatName('Cat2');  //Second category
$categories->attach($category);

$item->setCategories($categories);

same issue with the above code. It just saves the last (second) category. How can i add multiple categories to my item-object?

1

1 Answers

2
votes

Well i made a fatal error when using the SAME category-object. In fact i just changed its CatName value. In ORM we need one object for each "value". Means we can't use the same object for multiple "object-allocations" like i did above. So the correct way of achieving my purpose is:

$categories = $this->objectManager->get('TYPO3\CMS\Extbase\Persistence\ObjectStorage');

$category1 = $this->objectManager->get('VENDX\Items\Domain\Model\Category'); //1st catobj
$category1->setCatName('Cat1');  //First category
$categories->attach($category1);

$category2 = $this->objectManager->get('VENDX\Items\Domain\Model\Category'); //2nd catobj
$category2->setCatName('Cat2');  //Second category
$categories->attach($category2);

$item->setCategories($categories);

another "mistake" was using the objectManager for entities-instantiation. I was told to construct them via "new" instead of "overheading" the extension with the objectManager. so my final solution is:

$categories = new \TYPO3\CMS\Extbase\Persistence\ObjectStorage;

$category1 = new \VENDX\Items\Domain\Model\Category; //1st catobj
$category1->setCatName('Cat1');  //First category
$categories->attach($category1);

$category2 = new \VENDX\Items\Domain\Model\Category; //2nd catobj
$category2->setCatName('Cat2');  //Second category
$categories->attach($category2);

$item->setCategories($categories);