1

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 Answers 2

4

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; } 
Sign up to request clarification or add additional context in comments.

5 Comments

And how I can display them in listing page?
What Alessandro explaind is called self-reference. If you extract an ArrayCollection than you just call $currentItem->getParent()->getTitle();
@MuhammadShahzad as BDS wrote is correct you just call $currentItem->getParent()->getTitle();
@BDS can you please explain ArrayCollection as a new answer?
How can I get the parent category name in Symfony template file?
1

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.