2011-05-26 109 views
43

我有我的實體之一的多對一的關係,像這樣空值:學說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。

+0

你有哪些實際創建記錄的代碼?你在使用MySQL嗎? – 2011-05-26 09:57:50

+0

@ abe-petrillo我正在使用MySQL 5.1。我用一個代碼示例更新了問題,並創建了一條記錄。 – 2011-05-26 11:29:54

+2

自己找到了。根據[學說註釋參考](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

回答

55
+37

'@ORM \ JoinColumn(nullable = false)' – Dmitriy 2013-01-21 10:23:40

+8

當使用'yml'格式時,請小心在'joinColumn'下添加此屬性,而不要在關係名稱下添加此屬性。我花了很長時間才發現它! – achedeuzot 2014-04-20 17:27:10

+0

答案中的鏈接返回'404 Not Found',需要更新 – 2016-08-09 14:33:41

1

只是因爲發佈@ zim32沒有告訴我們應該把語句,所以我不得不做出一個試驗和錯誤。

YAML:

manyToOne: 
    {field}: 
     targetEntity: {Entity} 
     joinColumn: 
      name: {field} 
      nullable: false 
      referencedColumnName: {id} 
     cascade: ['persist']