使用 注释为给定列设置默认值并为实体关系初始化集合非常简单:
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
}
}
如何使用 实现相同的目标YAML 而是定义,无需手动编写
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 中的 options 属性为列添加默认值。您可以在 doctrine annotation documentation 阅读更多信息.
注释示例:
/**
* @ORM\Column(type="bool", name="is_visible", options={"default": false})
*/
protected $isVisible;
YAML 示例:
isVisible:
type: boolean
column: is_visible
options:
default: false
关于symfony - 使用 YAML 的 Doctrine2 和 Symfony2 的默认列值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9526272/