Избегайте дублирования при попытке сохранения в 1-м элементах отношений

#php #symfony #doctrine-orm

#php #symfony #доктрина-orm

Вопрос:

Я хочу избежать дублирования при попытке сохранения, однако моя логика в контроллере, похоже, не работает, если в entity уже задано название бренда Brands . Поэтому, если я попытаюсь сохраниться Mercedes как название бренда, я получу эту ошибку «Бренд уже существует в базе данных». Что он должен сделать, так это просто избежать сохранения brands и просто сохранить cars объект с id brands помощью объекта of. Как я могу решить эту проблему?

 1 to Many (Brands to Cars)
 

Примечание: вариант удаления @UniqueEntity(fields="name", message = "The Brand already exists in database.") нежизнеспособен, потому что я использую brands тип формы сам по себе где-то еще в моем приложении.

введите описание изображения здесь

КОНТРОЛЛЕР

 $form = $this->createForm(new BothType(), null, array('action' => $this->generateUrl('both')));

$form->handleRequest($request);

if ($form->isValid())
{
    $brandsData = $form->get('brands')->getData();
    $carsData = $form->get('cars')->getData();

    $repo = $this->getDoctrine()->getRepository('CarBrandBundle:Brands');
    $brands = $repo->findByName($brandsData->getName());

    //If Brands doesn't exist yet
    if (! $brands)
    {
        $brands = new Brands();
        $brands->setName($brandsData->getName());
        $brands->setOrigin($brandsData->getOrigin());

        $cars = new Cars();
        $cars->setModel($carsData->getModel());
        $cars->setPrice($carsData->getPrice());
        $cars->setBrands($brands);

        $em = $this->getDoctrine()->getManager();
        $em->persist($brands);
        $em->persist($cars);
        $em->flush();
    }
    //If exists
    else
    {
        $cars = new Cars();
        $cars->setModel($carsData->getModel());
        $cars->setPrice($carsData->getPrice());
        $cars->setBrands($brands);

        $em = $this->getDoctrine()->getManager();
        $em->persist($cars);
        $em->flush();
    }

    return new Response('Brands ID:'. $brands->getId().'-Cars ID:'.$cars->getId());
}
 

ТИП ФОРМЫ

 class BothType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->setMethod('POST')
            ->setAction($options['action'])
            ->add('brands', new BrandsType())
            ->add('cars', new CarsType())
            ->add('button', 'submit', array('label' => 'Add'))
            ;
    }
} 
 

Бренды

 /**
 * @ORMEntity
 * @ORMTable(name="brands", uniqueConstraints={@ORMUniqueConstraint(columns={"name"})})
 * @UniqueEntity(fields="name", message = "The Brand already exists in database.")
 */
class Brands
{
    protected $id;
    protected $name;

    /**
     * @ORMOneToMany(targetEntity="Cars", mappedBy="brands")
     */
    protected $cars;

    public function __construct()
    {
        $this->cars = new ArrayCollection();
    }

    public function getId() { return $this->id; }
    public function setName($name) { $this->name = $name; return $this; }
    public function getName() { return $this->name; }

    public function addCar(CarBrandBundleEntityCars $cars)
    {
        $this->cars[] = $cars;
        return $this;
    }

    public function removeCar(CarBrandBundleEntityCars $cars)
    {
        $this->cars->removeElement($cars);
    }

    public function getCars()
    {
        return $this->cars;
    }
}
 

Автомобили

 /**
 * @ORMEntity
 * @ORMTable(name="cars")
 */
class Cars
{
    protected $id;
    protected $model;

    /**
     * @ORMManyToOne(targetEntity="Brands", inversedBy="cars")
     * @ORMJoinColumn(name="brands_id", referencedColumnName="id")
     */
    protected $brands;

    public function getId() { return $this->id; }
    public function setModel($model) { $this->model = $model; return $this; }
    public function getModel() { return $this->model; }

    public function setBrands(CarBrandBundleEntityBrands $brands = null)
    {
        $this->brands = $brands;
        return $this;
    }

    public function getBrands()
    {
        return $this->brands;
    }
}
 

Комментарии:

1. Я прочитал это, и руководство, однако, показалось мне очень запутанным. Не могли бы вы показать мне, где я должен внести коррективы.

2. Можете ли вы показать findByName() ?

3. $repo = $this->getEntityManager()->getRepository('CarBrandBundle:Brands'); $brands = $repo->findByName($name); return ($brands) ? false : true;

4. Я имею в виду показать определение функции $repo->findByName($name)

5. Это файл репозитория: namespace CarBrandBundleRepository; use DoctrineORMEntityRepository; class BrandsRepository extends EntityRepository { public function checkNameUniqueness($name) { $repo = $this->getEntityManager()->getRepository('CarBrandBundle:Brands'); $brands = $repo->findByName($name); //If found then uniqueness check should fail return ($brands) ? false : true; } }