从教义中的 many-to-many self-referenced 实体得到 children

get children from many-to-many self-referenced entity in doctrine

我有一个实体文章是self-referenced。

Article {
    
    //primary key
    private $id;

    //unique
    private $slug;

    /**
     * @ORM\ManyToMany(targetEntity=self::class, inversedBy="parents")
     * @ORM\JoinTable(
     *     name = "article_article",
     *     joinColumns = {@ORM\JoinColumn(name = "article_source", referencedColumnName = "id")},
     *     inverseJoinColumns = {@ORM\JoinColumn(name = "article_target", referencedColumnName = "id")}
     * )
     */

    private ?Collection $children;

    /**
     * @ORM\ManyToMany(targetEntity=self::class, mappedBy="children")
     */
    private ?Collection $parents;
}

我从请求中获取文章 slug,我需要获取该 slug 的所有相关文章。 我正在尝试使用 dql 来执行此操作,但即使是简单的查询

$queryBuilder = $this->createQueryBuilder('a');
        $queryBuilder->where('a.children = 1');

给我

Error: Invalid PathExpression. StateFieldPathExpression or SingleValuedAssociationField expected."

所以我需要这个sql

select a.slug from article a where a.id in (
    select aa.article_target from article a2 inner join article_article aa on a2.id = aa.article_source
        where a2.slug = 'article_slug'
    )

翻译成dql,谁能帮帮我? 我如何从 dql 寻址到 table article_article?

p.s。这个变体有效,但对我来说不是 suitable,出于某些原因,我需要 dql

$article = $repository->findOneBy($criteria);
$children = $article->getChildren();

在 Doctrine 查询生成器中,您使用实体(PHP class 值)作为参数。您想要在 parents/children 的 Collection 中查找具有特定 Article 的文章。您要使用 MEMBER OF 运算符。

存储库:

  public function findOneBySlug($slug): ?Article
  {
    return $this->createQueryBuilder('a')
                ->andWhere('a.slug = :val')
                ->setParameter('val', $slug)
                ->getQuery()
                ->getOneOrNullResult()
      ;
  }

  public function findChildrenOf(Article $article)
  {
    return $this->createQueryBuilder('a')
                ->where(':art MEMBER OF a.parents')
                ->setParameter('art', $article)
                ->getQuery()
                ->getResult()
      ;
  }

  public function findParentsOf(Article $article)
  {
    return $this->createQueryBuilder('a')
                ->where(':art MEMBER OF a.children')
                ->setParameter('art', $article)
                ->getQuery()
                ->getResult()
      ;
  }

控制器:

$article = $repository->findOneBySlug($slug);
$children = $repository->findChildrenOf($article);
$parents = $repository->findParentsOf($article);

Doctrine 将自动确定需要查询的字段和表,并为配置的数据库构建查询。