使用註釋是很簡單的給定列設置默認值和實體間關係初始化集合:使用YAML定義,而不是使用YAML與Doctrine2和Symfony2的默認列值?
use Doctrine\Common\Collections\ArrayCollection;
class Category
{
/**
* @ORM\Id
* @ORM\Column(type="integer")
* @ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* @ORM\OneToMany(targetEntity="Product", mappedBy="category")
*/
protected $products;
/**
* @ORM\Column(type="bool")
*/
protected $is_visible;
public function __construct()
{
$this->products = new ArrayCollection();
$this->is_visible = true; // Default value for column is_visible
}
}
如何同樣可以實現,而無需手動編寫Category.php
? __construct()
是唯一的方法嗎?
Acme\StoreBundle\Entity\Category:
type: entity
id:
id:
type: integer
generator: { strategy: AUTO }
fields:
is_visible:
type: bool
oneToMany:
products:
targetEntity: Product
mappedBy: category
沒有註釋對我來說很清楚(或許我的英語說得不好)。但是你確認了我的意思:使用YAML你必須編輯生成的PHP類來設置默認值,對嗎?沒有其他方式來做到這一點? – gremo 2012-03-02 01:45:46
無法使用註釋執行此操作。您必須手動添加構造方法並添加默認值。 – Sgoettschkes 2012-03-02 08:36:16
是的,正如你所說的和@Boo證實的那樣,你需要將你的默認值直接放到生成的PHP類中。我編輯了我的答案以突出這一事實。 – Matt 2012-03-02 15:27:12