Relationships in Doctrine

吃可爱长大的小学妹 提交于 2019-11-28 14:50:28

Add in your Category yml:

oneToMany:
    items:
        targetEntity: Namespace\TO\YOUR\Entity\Item
        mappedBy: category

Add in your Item yml:

   manyToOne:
    catregory:
        targetEntity: Namespace\TO\YOUR\Entity\Category
        inversedBy: items
        joinColumn:
            name: category_id
            referencedColumn: id

Add in your Item Entity:

    /**
 * @var Catregory
 */
protected $catregory;


public function setCategory(Catregory $catregory) {
    $this->catregory = $catregory;
}

public function getCatregory() {
    return $this->catregory;
}       

Add in your Category Entity:

use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection; 

.................

/**
 * @var Collection of Item
 */
protected $items;

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

public function getItems() {
    return $this->items;
}

public function setItems(Collection $items) {
    $this->items = $items;
}

public function addItem(Item $item) {
    if (!$this->Items->contains($item)) {
        $item->setCategory($this);
        $this->items->add($item);
    }
}

public function removeItem(Item $item) {
    if ($this->items->contains($item)) {
        $this->items->remove($item);
    }
}

public function clearItems() {
    $this->items->clear();
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!