使用Gedmo扩展在层次结构中获取Symfony / Doctrine实体的级别

时间:2015-04-14 12:57:52

标签: php symfony doctrine-orm doctrine sylius

我有一个表(ayrshireminis_car_category),它是用分层结构构建的。

我正在尝试使用Doctrine Gedmo extension来提取我在其他地方使用的“级别”成员变量,所以我期望父级的级别为1,孩子的级别为2,孙子等级为3等等......

这是我的映射实体:

AyrshireMinis\CarBundle\Entity\Category:
    type: entity
    table: ayrshireminis_car_category
    gedmo:
        tree:
            type: nested
    id:
        id:
            type: integer
            length: 11
            generator: { strategy: AUTO }
    fields:
        name:
            type: string
            length: 150
        active:
            type: boolean
            default: true
        position:
            type: integer
            length: 11
        level:
            type: integer
            gedmo:
                - treeLevel
        createdAt:
              type: datetime
              gedmo:
                  timestampable:
                      on: create
              column: created_at
        updatedAt:
            type: datetime
            gedmo:
                timestampable:
                    on: update
            column: updated_at
    manyToOne:
        parent:
            targetEntity: AyrshireMinis\CarBundle\Entity\Category
            inversedBy: children
            gedmo:
                - treeParent
        createdBy:
            targetEntity: \Sylius\Component\Core\Model\UserInterface
            joinColumn:
                nullable: false
                name: created_by
            gedmo:
                blameable:
                    on: create
        updatedBy:
            targetEntity: \Sylius\Component\Core\Model\UserInterface
            joinColumn:
                nullable: false
                name: updated_by
            gedmo:
                blameable:
                    on: update
    oneToMany:
        products:
            targetEntity: AyrshireMinis\CarBundle\Entity\Product
            mappedBy: category

通过此映射,我收到以下错误:

  

缺少属性:左,右在课堂上 -   AyrshireMinis \ CarBundle \ Entity \ Category 500内部服务器错误 -   InvalidMappingException

但是,我不想在我的表格中使用“左”和“右”列。我怎么能绕过这个?

1 个答案:

答案 0 :(得分:0)

在不改变架构且严重依赖Gedmo扩展的情况下,我能够像这样提取“级别”:

/**
 * get a numeric representation of the press category level
 * i.e. parent categories - 0, child categories - 1, grandchild categories - 2 etc...
 *
 * @return int
 */
public function getLevel()
{
    $level = 0;

    $category = $this;

    // parent category
    if ($category->hasParent() === false) {
        return $level;
    }

    while ($category = $category->getParent()) {
        $level++;
    }

    return $level;
}

/**
 * @return bool
 */
public function hasParent()
{
    return ($this->parent != null ? true : false);
}