2017-06-04 53 views
1

我有一個產品類別表,其中如果parent_id爲null,則存儲類別,如果不是null,則假定這是父類別,那麼它具有子類別。現在問題是我無法在列表頁面中顯示父類別名稱,那麼有人可以有一個想法如何在產品類別實體中建立關係?Symfony Parent子類別關係

Symfony version: 3.3

表結構:(PRODUCT_CATEGORY)

id 
    parent_id 
    slug 
    title 

enter image description here

我曾嘗試在產品分類實體此代碼,但它並沒有表現出任何的關係型數據:

class ProductCategory 
{ 
    /** 
    * @ORM\OneToMany(targetEntity="ProductCategory", mappedBy="parent") 
    * @ORM\JoinColumn(name="parent_id", referencedColumnName="id", nullable=true) 
    */ 
    private $parent; 

回答

3

我通常使用孩子和父母,這是我如何使用它:

/** 
    * One ProductCategory has Many ProductCategories. 
    * @ORM\OneToMany(targetEntity="ProductCategory", mappedBy="parent") 
    */ 
    private $children; 

    /** 
    * Many ProductCategories have One ProductCategory. 
    * @ORM\ManyToOne(targetEntity="ProductCategory", inversedBy="children") 
    * @ORM\JoinColumn(name="parent_id", referencedColumnName="id", nullable=true) 
    */ 
    private $parent; 

編輯

/** 
    * ProductCategory constructor. 
    */ 
    public function __construct() 
    { 
     $this->children = new ArrayCollection(); 
    } 

getter/setter方法,這東西:

/** 
    * @param ProductCategory $children 
    * @return $this 
    */ 
    public function addChildren (ProductCategory $children) 
    { 
     $this->children[] = $children; 

     return $this; 
    } 
+0

我怎樣才能在列表網頁顯示它們? –

+0

Alessandro的解釋稱爲自我引用。如果你提取一個ArrayCollection而不是你調用$ currentItem-> getParent() - > getTitle(); – BDS

+0

@MuhammadShahzad BDS寫道是正確的,你只需調用$ currentItem-> getParent() - > getTitle(); –

1

使用實體與自我引用,亞歷山德羅描述,那麼讓我們假設你使用$ qb - >(bla bla) - > getResult();到一個名爲$ categories的變量中。然後,你就必須來遍歷它這樣的:

foreach($categories as $category) { 
    echo $category->getTitle() . ' has parent ' . ($category->getParent() ? $category->getParent()->getTitle() : 'none'); 
} 

要了解更多關於陣列收集,閱讀:http://www.doctrine-project.org/api/common/2.3/class-Doctrine.Common.Collections.ArrayCollection.html