Symfony 5,Doctrine queryBuilder OneToMany 关系

Posted

技术标签:

【中文标题】Symfony 5,Doctrine queryBuilder OneToMany 关系【英文标题】:Symfony 5, Doctrine queryBuilder OneToMany Relationship 【发布时间】:2021-04-16 06:32:22 【问题描述】:

我需要有关 Symfony 5 Doctrine queryBuilder 的帮助。我需要找到一些 OneToMany 关系只有来自选定文件组的文件的项目。

Entity structure:
    Documents.php:
       Id
       Name: (string)
       FILES: (OneToMany DocumentsFiles.php)
    DocumentsFiles.php: 
            Id
            File: (OneToOne)
            FileGroup: (ManyToOne DocumentsFilesGroup.php)
            Documents: (ManyToOne Documents.php)
    DocumentsFilesGroup.php:
            Id
            Name: (string)
            ShortName: (string)
            Files: (OneToMany DocumentsFiles.php)

Database:
    Document
        ID, NAME, FILES (OneToMany)
        1, SomeName, [1, File, 1,2, File1, 1,3, File2, 1,4, File3, 2],
        2, SomeName1, [5, File4, 1,6, File5, 1]
        3, SomeName2, [12, File11, 2]
        4, SomeName3, [13, File12, 1]
        5, SomeName4, [16, File15, 2]
    DocumentsFileGroups
        Id, Name, ShortName
        1, Temporary, tmp
        2, Final, final
For example:
    I need document with temporary files only.
    Result:  
        2, SomeName1, [5, File4, 1,6, File5, 1]
        4, SomeName3, [13, File12, 1]

In DocumentRepository i have query:
$query->addSelect('nodeFiles')->leftJoin('node.files', 'nodeFiles')->leftJoin(\App\Entity\DocumentsFiles::class, 'nodeExt', Expr\Join::WITH, 'nodeExt.fileGroup IN (:documentsFileGroup) AND nodeExt.fileGroup NOT IN (:documentsNotFileGroup)')
                                        ->setParameter('documentsFileGroup', 1)
                                        ->setParameter('documentsNotFileGroup', 2);
But in results i have:
  (wrong) 1, SomeName, [1, File, 1,2, File1, 1,3, File2, 1,4, File3, 2],
  2, SomeName1, [5, File4, 1,6, File5, 1]
  4, SomeName3, [13, File12, 1]

有人有想法或线索吗? 感谢您的帮助。

【问题讨论】:

【参考方案1】:

使用innerJoin 而不是leftJoin DocumentsFiles 或者更好地将过滤条件放入where(),因为您不需要加入DocumentFiles 两次。它可能看起来像这样:

$query->addSelect('nodeFiles')
    ->innerJoin('node.files', 'nodeFiles')
    ->where($query->expr()->eq('nodeFiles.fileGroup', ':documentsFileGroup'))
    ->andWhere($query->expr()->neq('nodeExt.fileGroup', ':documentsNotFileGroup'))
    ->setParameter('documentsFileGroup', 1)
    ->setParameter('documentsNotFileGroup', 2);

【讨论】:

以上是关于Symfony 5,Doctrine queryBuilder OneToMany 关系的主要内容,如果未能解决你的问题,请参考以下文章

Symfony 5 和 Doctrine,找不到使用 3 个相关实体获取结果的方法

“名称解析中的临时失败”:Symfony 5.3 使用 Doctrine 和 Docker 连接到 MariaDB

Symfony 3.4没有元数据类来处理错误

Symfony 5 中的 Doctrine Gedmo-Extension (Timestampable, Softdeletable ...) 有替代品吗?

Symfony 2 + Doctrine 2 + PHPUnit 3.5:闭包异常的序列化

Doctrine 2.5 意外的关联获取行为 [Symfony 3]