所以我想说我有一个实体类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
?
感谢您的帮助......请询问是否有任何不清楚的地方!
答案 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