且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

父母与子女关系与单一实体在教义中2

更新时间:2023-09-11 23:20:40

这应该是有效的:

<?php

use Doctrine\Common\Collections\ArrayCollection;

/** @ORM\Entity */
class Category {
    /**
     * @ORM\OneToMany(targetEntity="Category", mappedBy="parent")
     */
    protected $children;

    /**
     * @ORM\ManyToOne(targetEntity="Category", inversedBy="children")
     * @ORM\JoinColumn(name="parent", referencedColumnName="id")
     */
    private $parent;

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

    // Once you have that, accessing the parent and children should be straight forward 
    // (they will be lazy-loaded in this example as soon as you try to access them). IE:

    public function getParent() {
        return $this->parent;
    }

    public function getChildren() {
        return $this->children;
    }

    // always use this to setup a new parent/child relationship
    public function addChild(Category $child) {
       $this->children[] = $child;
       $child->setParent($this);
    }

    public function setParent(Category $parent) {
       $this->parent = $parent;
    }

}