Answer the question
In order to leave comments, you need to log in
Doctrine - A new entity was found through the relationship. Where is the mistake?
Good day.
There are such entities:
There was a task to create a "many-to-many" relationship between categories and brands. The following console solution is written:
public function parseBrands()
{
$em = $this->em;
$categories = $em->getRepository('MainCatalogBundle:Categories')->findAll();
foreach ($categories as $category) {
$products = $category->getProducts();
echo $category->getId();
foreach ($products as $iteration => $product) {
$brand = $product->getBrand();
if (!$brand || $category->getBrands()->contains($brand)) {
break;
}
$category->getBrands()->add($brand);
$brand->getCategories()->add($category);
if ($iteration % 200 === 0) {
$em->flush();
$em->clear();
}
}
$em->flush();
$em->clear();
}
}
[Doctrine\ORM\ORMInvalidArgumentException]
A new entity was found through the relationship 'Main\CatalogBundle\Entity\Brand#categories' that was not configured to cascade persist operations for
entity: Main\CatalogBundle\Entity\[email protected] To solve this issue: Either explicitly call EntityManager#persist() on this unkn
own entity or configure cascade persist this association in the mapping for example @ManyToOne(..,cascade={"persist"}). If you cannot find out which entit
y causes the problem implement 'Main\CatalogBundle\Entity\Categories#__toString()' to get a clue.
Answer the question
In order to leave comments, you need to log in
Rewriting the code like this solved the problem.
public function parseBrands()
{
$em = $this->em;
for ($iteration = 2637; $iteration < 3144; $iteration += 1) {
$category = $em->getRepository('MainCatalogBundle:Categories')->findOneBy(
array(
'id' => $iteration,
)
);
if ($category) {
echo $category->getId();
foreach ($category->getProducts() as $product) {
$brandId = $product->getBrand()->getId();
$brand = $em->getRepository('MainCatalogBundle:Brand')->findOneBy(
array(
'id' => $brandId,
)
);
if (!$brand || $category->getBrands()->contains($brand)) {
break;
}
$category->getBrands()->add($brand);
$brand->getCategories()->add($category);
$em->flush();
}
$em->clear();
}
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question