【问题标题】:Sonata create two entities but doesn't associate them奏鸣曲创建两个实体但不关联它们
【发布时间】:2014-08-11 13:26:17
【问题描述】:

在奏鸣曲管理员中,我正在构建呈现功能表单的产品表单。我的数据库中的关系是:

ProductFeatures:FeaturesValues 1:n

产品:特征值 1:n

class ProductAdmin extends Admin
{
    protected function configureFormFields(FormMapper $formMapper)
    {
       $formMapper
         ->add('name')
         ->add('featureValues','collection', array(
                    'mapped' => true,
                    'type' => new \Bundle\Form\FeatureValueType(),
                    'allow_add' => true,
                ));
    }
}

特征值类型:

class FeatureValueType extends AbstractType
{

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('productFeature') 
            ->add('value')
        ;
    }

特征值形式呈现特征,因此新特征值自动与特征相关联。问题是当我尝试在产品表单中执行此操作时提交后我得到了新产品,我得到了与特性相关的新特性值,但产品与特性值不相关(product_feature_value 表中的 product_id 是空)。

我错过了什么?

【问题讨论】:

  • 您是否设置了 cascade-persist 并链接了您的实体,以便在创建和链接它们时以 PHP 方式反映 DB 方式?
  • 我设置了 cascade-persist,但我应该如何链接这些实体?你的意思是像“ManyToOne”这样的注释?如果那样的话 - 我也这样做了。
  • 类似:public function addEducation ($education) { $education->setUser($this); $this->educations[] = $education;返回$这个; } 那么你只需更新具有此类的对象
  • 但是我应该如何获得这个 $education 对象呢?在预存操作中,我不能从我所看到的。
  • 我在家的时候会给你写一个完整的答案。

标签: php forms symfony


【解决方案1】:

我会假设你的课程有这样的东西。

// ...
use Doctrine\Common\Collections\ArrayCollection;

class Product
{
  // ...

  /**
   * @ORM\OneToMany(targetEntity="FeatureValue", mappedBy="product", cascade={"persist"})
   */
  protected $featureValues;

  public function __construct() {
      $this->featureValues = new ArrayCollection();
  }
  // ...
  /**
   * Add products
   *
   * @param Path\To\Entity\FeatureValue $featureValues
   * @return Product
   */
   public function addFeatureValue(\Path\To\Entity\FeatureValues $feauteValues)
   {
      $featureValues->setProduct($this);
      $this->featureValues[] = $featureValues;

      return $this;
   }
}

class FeatureValue
{
  // ...

  /**
   * @ORM\ManyToOne(targetEntity="Product", inversedBy="featureValues")
   */
  protected $product;
}

这样您只需添加新的FeatureValue 即可更新Product 类。由于addFeatureValue() 方法的工作方式,它会自动连接这两个项目,如果你有一个新的FeatureValue 项目添加到你正在更新的Product 项目,它将自动保存到数据库中,因为你说所以在关系规则中。

【讨论】:

  • 是的,我在 prePersist 方法中做了类似的事情,它在那里工作,不幸的是你的方式不起作用..
  • 从我在产品中提交表单方法“addFeatureValue()”后注意到的内容甚至没有被调用。
  • 我想你应该向@Sonata 的团队询问这个问题
猜你喜欢
  • 2020-10-20
  • 2013-12-04
  • 2017-04-13
  • 1970-01-01
  • 2019-07-04
  • 1970-01-01
  • 1970-01-01
  • 2014-06-04
  • 1970-01-01
相关资源
最近更新 更多