1
votes

I have a Product Category table, where I have stored categories if parent_id is null then assume this is parent category if not null then it has child categories. Now the issue is I can't show parent category name in listing page, so can someone have an idea how to make a relation in Product Category entity?

Symfony version: 3.3

Table Structure:(product_category)

  id
  parent_id
  slug
  title

enter image description here

I have tried this code in ProductCategory entity but it doesn't show any relational data:

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

2 Answers

3
votes

I usually use children and parent and this is how I use It:

    /**
     * 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;

EDIT

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

Getters / Setters and this stuff:

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

       return $this;
   }
1
votes

Using entity with self reference, as Alessandro described, then let's say you have all your records extracted with doctrine using $qb->(bla bla bla)->getResult(); into a variable called $categories. Then you just have to iterate through it like that:

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

To understand more about array collection, read: http://www.doctrine-project.org/api/common/2.3/class-Doctrine.Common.Collections.ArrayCollection.html