Reputation: 61
I have problem with doctrine. My task is to set new Product with Category from other table. Category name is unique. Category and Product tables are in onetomany relation. When I make :
$brand = new Category();
$brand->setBrand('Beers');
$beer = new Product();
$beer->setModel('Bavaria');
$beer->setBrand($brand);
$em = $this->getDoctrine()->getManager();
$em->persist($brand);
$em->persist($beer);
$em->flush();
It's all fine. But when I make this query with other model name (p.ex. Heineken) I have duplicated brand name. I want to have 1 brand name like wine, vodka, beers. I don't want to create each time brand name if it exists when I make query. Thanks for answers.
Upvotes: 0
Views: 130
Reputation: 732
If you want to let the user choose amongst Categories you could use a form with an EntityType.
If you want to let the user type a name and create the category if it doesn't exist you could do it like this :
$newBrand = 'userInput';
$em = $this->getDoctrine()->getManager();
$category = $em->getRepository('YouBundle:YouEntity')->findOneBy(array('brand' => $newBrand));
if ($category == null) {
$category = new Category();
$category->setBrand($newBrand);
$em->persist($category);
}
$beer = new Product();
$beer->setModel('Bavaria');
$beer->setBrand($category); // If you need to use $category in you view don't forget $category->addProduct($beer);
$em->persist($beer);
$em->flush();
PS : mySQL has a create or update directive but I wouldn't advise it here since you will need to match all fields.
Upvotes: 1