Symfony 2 - 如何允许作为另一个实体的对象的实体变量为空?

时间:2017-01-03 13:48:13

标签: php symfony doctrine-orm symfony-2.8

所以我想说我有一个实体类Travel

<?php

namespace Bundle\TravelCostsBundle\Entity;

class Travel {

     ...

    /**
     *
     * @var \Bundle\TravelCostsBundle\Entity\MilageAllowance
     */
    private $milageAllowance;

    ...

    /**
     * Set milageAllowance
     *
     * @param \Bundle\TravelCostsBundle\Entity\MilageAllowance $milageAllowance         
     *
     * @return Travel
     */
    public function setMilageAllowance(\Bundle\TravelCostsBundle\Entity\MilageAllowance $milageAllowance = null) {
        $this->milageAllowance = $milageAllowance;

        return $this;
    }

    /**
     * Get milageAllowance
     *
     * @return \Bundle\TravelCostsBundle\Entity\MilageAllowance
     */
    public function getMilageAllowance() {
        return $this->milageAllowance;
    }

    ...
}

这是Doctrine .yml文件:

# src/TravelCostsBundle/Resources/config/doctrine/Travel.orm.yml
Pec\Bundle\TravelCostsBundle\Entity\Travel:
  type: entity
  repositoryClass: Pec\Bundle\TravelCostsBundle\Repository\TravelRepository
  id:
    id:
      type: integer
      generator: {strategy: AUTO}
  ...
  oneToOne:
    milageAllowance:
      targetEntity: MilageAllowance
      mappedBy: travel
  fields:
    ...

应用程序使用Doctrine与数据库连接。我使用validation.yml文件验证实体,并使用表单创建类型Travel的实体,其中包含milageAllowance - 实体变量的字段。

我希望填充字段是可选的......

  • 如果字段为空$milageAllowance保持NULL并且(更重要的是)将不会创建数据库中的条目
    • 如果字段已填满,则将创建数据库中的条目。

是否可以使用oneToOne关系?

如何验证实体Travel只能有1个还是没有milageAllowance

感谢您的帮助......请询问是否有任何不清楚的地方!

2 个答案:

答案 0 :(得分:1)

您可以通过设置JoinColumn(nullable = true)将OneToOne关系设为可选

使用YML表示法,它看起来像这样:

    ...
  oneToOne:
    milageAllowance:
      targetEntity: MilageAllowance
      mappedBy: travel
  JoinColumn
    nullable: true 
  fields:
    ...

有关详细信息,请参阅此页:

http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/association-mapping.html

答案 1 :(得分:0)

感谢Stas Parshin,它给了我一部分答案。因此,请在nullable: true文件中设置orm

Travel.orm.yml

Projekt\Bundle\MyBundle\Entity\Travel:
  oneToOne:
    milageAllowance:
      targetEntity: MilageAllowance
      mappedBy: travel
      JoinColumn:
        nullable: true

TravelType类中,将添加的ReceiptType表单设置为'required' => false

class TravelType extends AbstractType {

    public function buildForm(FormBuilderInterface $builder, array $options) {
        $builder
            ->add('milageAllowance', MilageAllowanceType::class, array(
                'required'      => false,
            //Are all fields of milageAllowance empty => $travel->milageAllowance == NULL
                ...
        ))

如果所有字段都ReceiptType为空,则表示$travel->milageAllowance == NULL