Relationships in Doctrine

后端 未结 1 1175
借酒劲吻你
借酒劲吻你 2020-12-12 08:27

I have 2 Entities: Categories and products. How can I build a relationship between these Entities? Category Entity:

    class Category
    {
        private          


        
相关标签:
1条回答
  • 2020-12-12 08:43

    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();
    }
    
    0 讨论(0)
提交回复
热议问题