如何在ManyToOne字段上为exsting实体设置默认值

时间:2017-11-06 22:49:42

标签: php symfony doctrine

我正在尝试将ManyToOne列添加到已存在的表中,其中包含行。 我希望它是nullable=false

由于它不可为空,我正在尝试设置默认值,但没有选项可以执行此操作。 如果我没有设置默认值,则shema更新崩溃并且无法创建外键,因为在我创建的表中没有id为0的行

外键引用的表的代码:

<?php

namespace MyBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints;

/**
 * @ORM\Table(name="authority")
 * @ORM\Entity()
 */
class Authority
{
    /**
     * @var int
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * @var string
     * @Constraints\NotBlank(message="name cannot be blank.")
     * @ORM\Column(type="string")
     */
    protected $name;

    /**
     * @var \DateTime
     *
     * @ORM\Column(name="created_at", type="datetime", nullable=true)
     */
    protected $createdAt;

    /**
     * Authority constructor.
     */
    public function __construct()
    {
        $this->createdAt = new \DateTime();
    }
}

我要添加外键的表的代码:

/**
 * @var Authority
 * @ORM\ManyToOne(targetEntity="MyBundle\Entity\authority", cascade={"persist"})
 * @ORM\JoinColumn(referencedColumnName="id", nullable=false)
 */
protected $authority;

我试过了:

protected $authority = 1;

 * @ORM\JoinColumn(referencedColumnName="id", nullable=false, default=1)

public function __construct()
{
    $this->authority = 1;
}

我不想手动更改数据库。

2 个答案:

答案 0 :(得分:0)

/**
 * @var Authority
 * @ORM\ManyToOne(targetEntity="MyBundle\Entity\authority", cascade={"persist"})
 * @ORM\JoinColumn(referencedColumnName="id", nullable=false, columnDefinition="INT DEFAULT 1")
 */
protected $authority;

这可以解决自动生成的迁移类中的问题。

答案 1 :(得分:0)

您可以为被引用表的主键设置默认值。看看options={"default"=1}

/**
 * @ORM\Table(name="authority")
 * @ORM\Entity()
 */
class Authority
{
    /**
     * @var int
     * @ORM\Id
     * @ORM\Column(type="integer", options={"default"=1})
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;