首页 > 解决方案 > Doctrine 不会更新/生成 ManyToOne 和 OneToMany 的字段

问题描述

我有一个当前工作正常的超类(所有关系和属性都更新到数据库)

    use Doctrine\Common\Collections\ArrayCollection;
    use Doctrine\ORM\Mapping\Column;
    use Doctrine\ORM\Mapping\Table;
    use Doctrine\ORM\Mapping\Entity;
    use Doctrine\ORM\Mapping\Id;
    use Doctrine\ORM\Mapping\GeneratedValue;
    use Doctrine\ORM\Mapping\ManyToOne;
    use Doctrine\ORM\Mapping\OneToMany;
    use Doctrine\ORM\Mapping\JoinColumn;

    use JMS\Serializer\Annotation as JMS;

    /**
     * Document
     *
     * @Table(name="document")
     * @Entity(repositoryClass="AcmeBundleDocumentRepository")
     */

    class Document
    {

        /**
         * @var string
         *
         * @Column(name="id", type="string")
         * @Id
         * @GeneratedValue(strategy="UUID")
         */
        protected $id;

        /**
         * @var string
         * @Column(name="name", type="string", length=255)
         */
        protected $name;

        /**
         * @var string
         * @Column(name="type", type="string", length=255)
         */
        protected $type;

        /**
         * @var boolean
         * @Column(name="has_attachments", type="boolean")
         */
        protected $hasAttachments;

        /**
         * @ManyToOne(targetEntity="Delivery")
         * @JoinColumn(name="delivery_id", referencedColumnName="id", nullable=false)
         * @JMS\Exclude()
         */
        protected $delivery;

        /**
         * @OneToMany(targetEntity="Extension", mappedBy="document", cascade={"persist","remove"})
         **/
        protected $extensions;

        public function __construct()
        {
            $this->extensions = new ArrayCollection();
        }

        /* getter and setters */

}

现在我创建了一个名为的实体Note,它扩展到Document实体

use Doctrine\ORM\Mapping\Table;
use Doctrine\ORM\Mapping\Entity;

    /**
     * Note
     *
     * @Table(name="note")
     * @Entity(repositoryClass="NoteRepository")
     */
    class Note extends Document
    {

    }

我认为表/实体note应该生成与扩展类相同的东西。但不要这样做

我跑php bin/console doctrine:schema:update -f

这只会生成属性而不是 FK(外键),在这种情况下@ManyToOne@OneToMany.

另外可能对我们有帮助,我在同一个数据库中有这些实体

我做错了什么?

标签: symfonydoctrine-ormdoctrine

解决方案


根据文档,我认为您缺少@MappedSuperclass注释,或者您以错误的方式使用 Doctrine 继承。请注意,aMappedSupperClass本身并不是一个实体,而只是一个用于在子类之间共享公共方法和属性的类(您应该已经知道相同的继承概念)。

/**
 * @MappedSuperclass
 */
class DocumentSuperClass
{
    ...
}

/**
 * @Table(name="document")
 * @Entity(repositoryClass="AcmeBundleDocumentRepository")
 */
class Document extends DocumentSuperClass
{
    ...
}

/**
 * @Table(name="note")
 * @Entity(repositoryClass="NoteRepository")
 */
class Note extends DocumentSuperClass
{
    ...
}

推荐阅读