我有我的實體之一的多對一的關係,像這樣空值:學說2 - 不允許在多對一關係的外鍵
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;
// ...
}
這生成一個數據庫模式,其中許可證「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();
基本上,我不希望,而不必分配給客戶要堅持許可證它。是否有一些註釋需要設置,或者我是否需要將一個Customer對象傳遞給我的許可證構造函數?
我使用的數據庫引擎是MySQL v5.1,我在Symfony2應用程序中使用Doctrine 2。
你有哪些實際創建記錄的代碼?你在使用MySQL嗎? – 2011-05-26 09:57:50
@ abe-petrillo我正在使用MySQL 5.1。我用一個代碼示例更新了問題,並創建了一條記錄。 – 2011-05-26 11:29:54
自己找到了。根據[學說註釋參考](http://www.doctrine-project.org/docs/orm/2.0/en/reference/annotations-reference.html#joincolumn),對於''nullable''有'nullable'選項, @ Column'和'@ JoinColumn'註解。將其設置爲false會導致我想要的行爲。 – 2011-05-26 13:19:57