Symfony完整性约束违规:1062重复条目' 1'为了钥匙

时间:2016-03-19 03:15:57

标签: php forms symfony entity crud

我意识到我的错误,但我不知道如何解决它。 我有两个表,Car和Advertisement,我希望执行一个嵌套表单来将数据添加到表中。但是我有一条错误信息,上面写着:

执行

时发生异常
INSERT INTO car (year, model, engine_size, colour, mileage, advertisement_id, fuel_id, transmission_id, body_id, make_id) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)

使用params ["2012", "a3", "v8", "45", 4, 26, 1, 1, 1, 1]

例外:

SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '1' for key 'UNIQ_773DE69D78D28519'

我的问题是:为什么我的方法不会检索我的实体的ID以将其放入实体广告中?

关系

 /**
 *
 * @ORM\OneToOne(targetEntity="Home\HomeBundle\Entity\Advertisement", cascade={"persist","remove"})
 * @ORM\JoinColumn(nullable=false)
 */
private $Advertisement;

public function setAdvertisement(\Home\HomeBundle\Entity\Advertisement $advertisement)
{
    $this->Advertisement = $advertisement;

    return $this;
}

表格

class CarType extends AbstractType
{

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder
        ->add('year')
        ->add('model')
        ->add('engineSize')
        ->add('colour')
        ->add('mileage')
        ->add('Advertisement', new AdvertisementType())
        ->add('Fuel')
        ->add('Transmission')
        ->add('Body')
        ->add('Make')
    ;
}

/**
 * @param OptionsResolverInterface $resolver
 */
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
    $resolver->setDefaults(array(
        'data_class' => 'Home\HomeBundle\Entity\Car'
    ));
}

/**
 * @return string
 */
public function getName()
{
    return 'home_homebundle_car';
}
}

控制器

public function createAction(Request $request)
{
    $entity = new Car();
    $form = $this->createCreateForm($entity);
    $form->handleRequest($request);

    if ($form->isValid()) {
        $em = $this->getDoctrine()->getManager();
        $em->persist($entity);
        $em->flush();

        return $this->redirect($this->generateUrl('car_show', array('id' => $entity->getId())));
    }

    return $this->render('HomeBundle:Car:new.html.twig', array(
        'entity' => $entity,
        'form'   => $form->createView(),
    ));
}

/**
 * Creates a form to create a Car entity.
 *
 * @param Car $entity The entity
 *
 * @return \Symfony\Component\Form\Form The form
 */
private function createCreateForm(Car $entity)
{
    $form = $this->createForm(new CarType(), $entity, array(
        'action' => $this->generateUrl('car_create'),
        'method' => 'POST',
    ));

    $form->add('submit', 'submit', array('label' => 'Create'));

    return $form;
}

1 个答案:

答案 0 :(得分:1)

一对一关系,您的数据库中有一个具有相同ID的实体。