使用注释是很简单的给定列设置默认值和初始化实体间关系的集合:
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
我想是因为默认值是通过普通的PHP设置你误会注释莫名其妙。
/**
* @ORM\Column(type="bool") <- This is an annotation
*/
protected $is_visible;
public function __construct()
{
$this->products = new ArrayCollection(); // <- This is not an annotation
$this->is_visible = true; // <- This is not an annotation
}
有使用默认值YAML映射没有区别。原因很简单,在这里你类是如何寻求与注释:
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映射:
use Doctrine\Common\Collections\ArrayCollection;
class Category
{
protected $id;
protected $products;
protected $is_visible;
public function __construct()
{
$this->products = new ArrayCollection();
$this->is_visible = true; // Default value for column is_visible
}
}
在第二个例子不同的是没有更多说明,因为该映射是通过YAML完成。在类的构造完全相同做了同样的。因此,默认值设定在以纯PHP进行施工时间。
有注释和YAML映射这个任务之间没有什么区别。因此,底线是,你需要编辑生成的PHP类来把你的默认值。有没有办法可以将其设置在YAML,让学说把这段代码给你,至少,在我们说话的时间。
也许我误解你的问题:),如果是的话,不要犹豫,指正。
希望能帮助到你。
问候, 马特
您可以使用选项属性在注释或YAML列添加默认值。你可以阅读更多的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
您可以尝试添加缺省值与columnDefinition,但它是DDL,它依赖于特定的DBMS(坏事)。下面您的示例中,场* is_visible *使用MySQL:
is_visible:
type: bool
columnDefinition: is_visible tinyint(1) NOT NULL DEFAULT '1'
在一般情况下,这不是一个好主意,你是鼓励代码实体类中使用构造方法或属性初始化...
时间已经过去了。现在,您可以通过YAML列设置默认值。
columnName:
type: string
options:
default: "someText"