简体   繁体   English

如何在Doctrine中使用MySQL数据库中的变量?

[英]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. 我想有1个品牌名称,例如葡萄酒,伏特加酒,啤酒。 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. 如果要让用户在类别中进行选择,则可以使用带有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. PS:mySQL有一个create或update指令,但是在这里我不建议这样做,因为您需要匹配所有字段。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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