如果DB中存在图库名称,该怎么办?

时间:2017-11-06 16:07:04

标签: symfony symfony-3.2 symfony-3.1 symfony3.x

public function createGalleryAction(Request $ request){

opennlp.bat

请提及验证码的放置位置,我是Symfony的新手。

2 个答案:

答案 0 :(得分:0)

//Entity Gallery

use Symfony\Component\Validator\Constraints as Assert;

/**
* @ORM\Entity
* @UniqueEntity("galleryName")
*/
class Gallery
{
/**
 *
 * @ORM\Column(name="galleryName", type="string", length=255, unique=true)
 */
protected $galleryName;

// ...
}

https://symfony.com/doc/current/reference/constraints/UniqueEntity.html

如果你想使用教义:

$galleryName = $gallery_form['galleryName']->getData();

$galleryExist = $em->getRepsitory('AppBundle:Gallery')->findOneByGalleryName($galleryName);
  if($galleryExisty){
   // do something
  }

答案 1 :(得分:0)

它实际上取决于您的数据库架构。如果图库名称被定义为唯一(您应该这样做,因为您希望避免重复名称), $ em-> flush()会引发错误。因此,您应该使用try catch语句封装代码:

try {
  // add your logic here, ex:
  ...
  ...
  $em->persist($gallery);

} catch(\Exception $ex) {

 // do whatever you want with your error here, ex:
 $session->getFlashBag()->add('error', 'Gallery already exists');
 return $this->render('admin/addgallery.html.twig', [
            'gallery_form' => $gallery_form->createView()
 ]);

}