简体   繁体   中英

How to use variable from mySQL DB in Doctrine?

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM