使用 Native SQL 的 Doctrine 递归查询隐藏父列

问题描述 投票:0回答:1

我的函数如下所示:

    public function findRecursiveByParentOrId(int $parentId, string $column): array
    {
        $rsm = new ResultSetMapping();
        $rsm->addEntityResult(Division::class, 'div');
        $rsm->addFieldResult('div', 'id', 'id');
        $rsm->addFieldResult('div', 'name', 'name');
        $rsm->addFieldResult('div', 'description', 'description');
        $rsm->addFieldResult('div', 'parent', 'parent_id');

        $query = $this->getEntityManager()->createNativeQuery('
            WITH RECURSIVE cte (id, name, description, parent_id) AS (
                SELECT id, name, description, parent_id FROM division
                WHERE ' . $column . ' = ?
                UNION ALL
                    SELECT d.id, d.name, d.description, d.parent_id FROM division d
                    INNER JOIN cte
                        ON d.parent_id = cte.id
            )
            SELECT * FROM cte;
        ', $rsm);
        $query->setParameter(1, $parentId);

        return $query->getArrayResult();
    }

来自实体:

     /**
     * @ORM\ManyToOne(targetEntity=Division::class, inversedBy="children")
     * @ORM\JoinColumn(name="parent_id", referencedColumnName="id", nullable=true)
     */
    private ?Division $parent = null;

结果:

array:5 [▼
  0 => array:3 [▼
    "id" => 1
    "name" => "Personal Abteilung"
    "description" => "Personal Abteilung"
  ]...

我找不到获取结果中的parent_id 列的方法!我尝试了很多可能性但没有成功。我做错了什么?

在每个需要的地方用parent_id替换父列的名称。

symfony doctrine-orm doctrine common-table-expression recursive-query
1个回答
0
投票

ça 为我而行:

$rsm = new ResultSetMapping();
$rsm->addEntityResult(Locality::class, 'l');
$rsm->addFieldResult('l', 'id', 'id');
$rsm->addFieldResult('l', 'name', 'name');
$rsm->addFieldResult('l', 'parent', 'parent_id');
$rsm->addJoinedEntityResult(Locality::class, 'p', 'l', 'parent');
$rsm->addFieldResult('p', 'parent_id', 'id');

$query = $this->getEntityManager()->createNativeQuery('
WITH RECURSIVE locality_tree AS ( 
        SELECT id, parent_id FROM locality WHERE parent_id IS NULL 

        UNION ALL 

        SELECT  l.id, l.parent_id FROM locality l JOIN locality_tree lt ON l.parent_id = lt.id
      ) 
      SELECT l.id, l.name,  l.parent_id FROM locality_tree lt LEFT JOIN locality l ON lt.id = l.id  

', $rsm);

return $query->getArrayResult();
© www.soinside.com 2019 - 2024. All rights reserved.