[英]Symfony Parent Child category relation
我有一个产品类别表,如果parent_id为null,则存储了类别,如果不是null,则假定为父类别,则具有子类别。 现在的问题是我无法在列表页面中显示父类别名称,因此有人可以知道如何在“产品类别”实体中建立关系吗?
Symfony version: 3.3
表结构:(product_category)
id
parent_id
slug
title
我已经在ProductCategory实体中尝试了此代码,但未显示任何关系数据:
class ProductCategory
{
/**
* @ORM\OneToMany(targetEntity="ProductCategory", mappedBy="parent")
* @ORM\JoinColumn(name="parent_id", referencedColumnName="id", nullable=true)
*/
private $parent;
我通常使用孩子和父母,这就是我的用法:
/**
* 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();
}
Getters / Setters和以下内容:
/**
* @param ProductCategory $children
* @return $this
*/
public function addChildren (ProductCategory $children)
{
$this->children[] = $children;
return $this;
}
如Alessandro所述,使用带有自引用的实体,然后假设您使用$ qb->(bla 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.