symfony - 使用 YAML 的 Doctrine2 和 Symfony2 的默认列值?

标签 symfony doctrine doctrine-orm

使用 注释为给定列设置默认值并为实体关系初始化集合非常简单:

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/

相关文章:

symfony1 - symfony 统计用户数

php - Doctrine 2 - 使用类表继承时的访问级别问题

php - Symfony2 中的 Doctrine 分页器 - 我如何使用这个东西?

php - 使用 Symfony/Doctrine 的 Memcache 正在重新加载数据

php - Doctrine 2 : Best way to handle many-to-many with extra columns in reference table

sqlite - 存储我的服务 sqlite 数据库文件的最佳位置?

php - Doctrine 和 DateTime 显示出错误的差异

symfony - 如何获取 Twig 中所选 ChoiceType 的值?

php - 将数组传递给 Symfony 中的 Twig 宏

php - 类别树的路由