Symfony2在插入两侧的一部分之前,尝试插入多个关系

Symfony2在插入两侧的一部分之前,尝试插入多个关系,symfony,doctrine-orm,symfony-2.3,Symfony,Doctrine Orm,Symfony 2.3,我有以下几点: <?php namespace ProductBundle\Entity; use Doctrine\ORM\Mapping as ORM; use Gedmo\Mapping\Annotation as Gedmo; use ProductBundle\DBAL\Types\StatusType; use ProductBundle\DBAL\Types\FieldType; use Fresh\Bundle\DoctrineEnumBundle\Validator\

我有以下几点:

<?php

namespace ProductBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Gedmo\Mapping\Annotation as Gedmo;
use ProductBundle\DBAL\Types\StatusType;
use ProductBundle\DBAL\Types\FieldType;
use Fresh\Bundle\DoctrineEnumBundle\Validator\Constraints as DoctrineAssert;

/**
 * @ORM\Entity
 * @ORM\Table(name="product_detail")
 */
class ProductDetail {

    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * @ORM\ManyToOne(targetEntity="ProductDetail")
     * @ORM\JoinColumn(name="parent", referencedColumnName="id")
     */
    protected $parent;

    /**
     * @ORM\Column(type="string", length=255)
     */
    protected $description;

    /**
     * @ORM\Column(type="string", length=255)
     */
    protected $label;

    /**
     * @var string $field_type
     * @DoctrineAssert\Enum(entity="ProductBundle\DBAL\Types\FieldType")
     * @ORM\Column(name="field_type", type="FieldType", nullable=false)
     */
    protected $field_type;

    /**
     * @ORM\Column(name="values_text", type="string")
     */
    protected $values_text;

    /**
     * @ORM\Column(type="string", length=255)
     */
    protected $measure_unit;

    /**
     * @var string $status
     * @DoctrineAssert\Enum(entity="ProductBundle\DBAL\Types\StatusType")
     * @ORM\Column(name="status", type="StatusType", nullable=false)
     */
    protected $status;

    /**
     * @Gedmo\Timestampable(on="create")
     * @ORM\Column(name="created", type="datetime")
     */
    protected $created;

    /**
     * @Gedmo\Timestampable(on="update")
     * @ORM\Column(name="modified", type="datetime")
     */
    protected $modified;

    /**
     * @ORM\ManyToMany(targetEntity="CategoryBundle\Entity\Category", inversedBy="pd_detail")
     * @ORM\JoinTable(name="product_detail_has_category",
     *      joinColumns={@ORM\JoinColumn(name="category", referencedColumnName="id")},
     *      inverseJoinColumns={@ORM\JoinColumn(name="detail", referencedColumnName="id")}
     *      )
     */
    protected $category;

    /**
     * @ORM\ManyToMany(targetEntity="ProductBundle\Entity\DetailGroup", inversedBy="productDetail")
     * @ORM\JoinTable(name="detail_group_has_product_detail",
     *      joinColumns={@ORM\JoinColumn(name="group", referencedColumnName="id")},
     *      inverseJoinColumns={@ORM\JoinColumn(name="detail", referencedColumnName="id")}
     *      )
     */
    protected $detail_group;

    public function __construct() {
        $this->detail_group = new \Doctrine\Common\Collections\ArrayCollection();
        $this->category = new \Doctrine\Common\Collections\ArrayCollection();
    }

    public function getId() {
        return $this->id;
    }

    public function setParent(ProductDetail $parent = null) {
        $this->parent = $parent;
    }

    public function getParent() {
        return $this->parent;
    }

    public function setDescription($description) {
        $this->description = $description;
    }

    public function getDescription() {
        return $this->description;
    }

    public function setLabel($label) {
        $this->label = $label;
    }

    public function getLabel() {
        return $this->label;
    }

    public function setFieldType($field_type) {
        $this->field_type = $field_type;
    }

    public function getFieldType() {
        return $this->field_type;
    }

    public function setValuesText($values_text) {
        $this->values_text = $values_text;
    }

    public function getValuesText() {
        return $this->values_text;
    }

    public function setMeasureUnit($measure_unit) {
        $this->measure_unit = $measure_unit;
    }

    public function getMeasureUnit() {
        return $this->measure_unit;
    }

    public function setStatus($status) {
        $this->status = $status;
    }

    public function getStatus() {
        return $this->status;
    }

    public function setCreated($param) {
        $this->created = $param;
        return true;
    }

    public function getCreated() {
        return $this->created;
    }

    public function setModified($param) {
        $this->modified = $param;
        return true;
    }

    public function getModified() {
        return $this->modified;
    }

    public function setCategory(Category $category) {
        $this->category[] = $category;
    }

    public function getCategory() {
        return $this->category;
    }

    public function setDetailGroup(DetailGroup $detailGroup) {
        $this->detail_group[] = $detailGroup;
    }

    public function getDetailGroup() {
        return $this->detail_group;
    }

}
这是我的
ProductDetailType.php
表单:

<?php

namespace ProductBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;

class ProductDetailType extends AbstractType {

    public function buildForm(FormBuilderInterface $builder, array $options) {
        $builder
                ->add('category', 'entity', array('class' => 'CategoryBundle:Category', 'property' => 'name', 'required' => false, 'multiple' => true, 'expanded' => false))
                ->add('detail_group', 'entity', array('class' => 'ProductBundle:DetailGroup', 'property' => 'name', 'required' => false, 'multiple' => true, 'expanded' => false))
                ->add('parent', 'entity', array('class' => 'ProductBundle:ProductDetail', 'property' => 'label', 'required' => false))
                ->add('description', 'text', array('required' => false))
                ->add('label')
                ->add('field_type', 'choice', ['choices' => \ProductBundle\DBAL\Types\FieldType::getChoices()])
                ->add('values_text', 'collection', array('type' => 'text', 'allow_add' => true, 'allow_delete' => true, 'by_reference' => false))
                ->add('measure_unit', 'text', array('required' => false))
                ->add('status', 'choice', ['choices' => \ProductBundle\DBAL\Types\StatusType::getChoices()]);
    }

    public function setDefaultOptions(OptionsResolverInterface $resolver) {
        $resolver->setDefaults(array(
            'data_class' => 'ProductBundle\Entity\ProductDetail'
        ));
    }

    public function getName() {
        return 'prod_detail_create';
    }

}
当我尝试插入新记录时,会出现以下错误:

执行“插入到”时发生异常 产品“详细信息”具有“类别(类别,详细信息)”值(?,)”和 参数[7,2]:

SQLSTATE[23000]:完整性约束冲突:1452无法添加或 更新子行:外键约束失败 (
产品详细信息\u有\u类别
,限制
fk\u产品\u详细信息\u具有\u类别\u产品\u详细信息1
外键 (
detail
)参考
product\u detail
id
)更新级联)

我查看了日志并看到以下内容:

DEBUG - "START TRANSACTION"
DEBUG - INSERT INTO product_detail (description, label, field_type, values_text, measure_unit, status, created, modified, parent) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
DEBUG - INSERT INTO product_detail_has_category (category, detail) VALUES (?, ?)
DEBUG - "ROLLBACK" 
我不知道为什么它不插入产品详细信息,并且尝试创建关系,有什么问题吗?

您可以:

  • 设置在
    @manytomy
    中的
    $category
    字段集
    cascade={“PERSIST”}

    这不需要改变控制器本身,但取决于您是否喜欢定义级联

  • 在持久化
    ProductDetail
    之前手动持久化
    Category
    对象

    $em = ...; // your entity manager
    
    // first, manually persist any category that is found
    foreach ( $productDetail->getCategory() as $c ){ 
        $em->persist($c);
    }
    
    // then, persist top-level object
    $em->persist($productDetail);
    
    // finally, flush everything
    $em->flush();
    

希望这有点帮助…

我已经找到了错误所在,请参见下面注释中的更改:

/**
 * @ORM\ManyToMany(targetEntity="CategoryBundle\Entity\Category", inversedBy="pd_detail", cascade={"persist"})
 * @ORM\JoinTable(name="product_detail_has_category",
 *      joinColumns={@ORM\JoinColumn(name="detail", referencedColumnName="id")},
 *      inverseJoinColumns={@ORM\JoinColumn(name="category", referencedColumnName="id")}
 *      )
 */
protected $category;

/**
 * @ORM\ManyToMany(targetEntity="ProductBundle\Entity\DetailGroup", inversedBy="productDetail", cascade={"persist"})
 * @ORM\JoinTable(name="detail_group_has_product_detail",
 *      joinColumns={@ORM\JoinColumn(name="detail", referencedColumnName="id")},
 *      inverseJoinColumns={@ORM\JoinColumn(name="kgroup", referencedColumnName="id")}
 *      )
 */
protected $detail_group; 

我已经反转了joinColumns和inversedJoinColumns中的关系,一切正常,由于MySQL查询错误,还必须将组重命名为kgroup

我只测试了第一个解决方案,但仍然出现相同的错误,无法工作。另一方面,我无法保存第一个类别,因为类别已经存在,不存在的是
product\u detail
,因为当我保存表单时,表单没有创建,然后多对多插入失败,这就是问题所在
$em = ...; // your entity manager

// first, manually persist any category that is found
foreach ( $productDetail->getCategory() as $c ){ 
    $em->persist($c);
}

// then, persist top-level object
$em->persist($productDetail);

// finally, flush everything
$em->flush();
/**
 * @ORM\ManyToMany(targetEntity="CategoryBundle\Entity\Category", inversedBy="pd_detail", cascade={"persist"})
 * @ORM\JoinTable(name="product_detail_has_category",
 *      joinColumns={@ORM\JoinColumn(name="detail", referencedColumnName="id")},
 *      inverseJoinColumns={@ORM\JoinColumn(name="category", referencedColumnName="id")}
 *      )
 */
protected $category;

/**
 * @ORM\ManyToMany(targetEntity="ProductBundle\Entity\DetailGroup", inversedBy="productDetail", cascade={"persist"})
 * @ORM\JoinTable(name="detail_group_has_product_detail",
 *      joinColumns={@ORM\JoinColumn(name="detail", referencedColumnName="id")},
 *      inverseJoinColumns={@ORM\JoinColumn(name="kgroup", referencedColumnName="id")}
 *      )
 */
protected $detail_group;