Tob*_*ies 52 php relationship many-to-one doctrine-orm
我在我的一个实体中有一个ManyToOne关系,如下所示:
class License {
// ...
/**
* Customer who owns the license
*
* @var \ISE\LicenseManagerBundle\Entity\Customer
* @ORM\ManyToOne(targetEntity="Customer", inversedBy="licenses")
* @ORM\JoinColumn(name="customer_id", referencedColumnName="id")
*/
private $customer;
// ...
}
class Customer {
// ...
/**
* Licenses that were at one point generated for the customer
*
* @var \Doctrine\Common\Collections\ArrayCollection
* @ORM\OneToMany(targetEntity="License", mappedBy="customer")
*/
private $licenses;
// ...
}
Run Code Online (Sandbox Code Playgroud)
这将生成一个数据库模式,其中允许许可证表的"customer_id"字段为空,这正是我不想要的.
这里是一些代码,我创建一个记录来证明它确实允许引用字段的空值:
$em = $this->get('doctrine')->getEntityManager();
$license = new License();
// Set some fields - not the reference fields though
$license->setValidUntil(new \DateTime("2012-12-31"));
$license->setCreatedAt(new \DateTime());
// Persist the object
$em->persist($license);
$em->flush();
Run Code Online (Sandbox Code Playgroud)
基本上,我不希望在没有客户分配许可的情况下保留许可.是否需要设置一些注释,或者我是否只需要将Customer对象传递给我的许可证的构造函数?
我使用的数据库引擎是MySQL v5.1,我在Symfony2应用程序中使用Doctrine 2.
zim*_*m32 72
添加nullable = false到JoinColumn注释:
@ORM\JoinColumn(..., nullable=false)
Run Code Online (Sandbox Code Playgroud)
只是发帖,因为@zim32 没有告诉我们应该把声明放在哪里,所以我不得不进行反复试验。
亚米尔:
manyToOne:
{field}:
targetEntity: {Entity}
joinColumn:
name: {field}
nullable: false
referencedColumnName: {id}
cascade: ['persist']
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
24979 次 |
| 最近记录: |