Doctrine ORM如何在WHERE条件中计算ArrayCollection的数量

6

我想在使用Symfony2.8Doctrine 2.5时,在Doctrine ORM查询中过滤掉所有集合包含恰好3个元素的数据集。

$em = $this->getDoctrine()->getManager();
$query = $em->getRepository("AppBundle:EduStructItem")
->createQueryBuilder('e')
 ->addSelect('COUNT(e.preconditions) AS HIDDEN numberpre')
 ->having('numberpre = 3')
->getQuery();
$res = $query->getResult();
dump($res);
foreach ($res as $entity){
    print "title:".$entity->getTitle()."<br>";
    dump($entity->getPreconditions()->toArray());
}

preconditions是一个包含前提条件集合的数组集合。

最终,我想要获取所有恰好有3个前提条件的结果。此外,按照数组集合中值的数量排序也会很棒(类似于order by Count(e.preconditions))。

由于使用了另一个bundle,我从2.5.2版本降级到了2.5.0版本。虽然我不认为这是问题的原因,但为了完整起见,这里是我composer Show命令中Doctrine部分的内容:

data-dog/pager-bundle                v0.2.4             Paginator bundle for symfony2 and doctrine orm, allows customization with filters and sorters
  doctrine/annotations                 v1.2.7             Docblock Annotations Parser
  doctrine/cache                       v1.5.2             Caching library offering an object-oriented API for many cache backends
  doctrine/collections                 v1.3.0             Collections Abstraction library
  doctrine/common                      v2.5.2             Common Library for Doctrine projects
  doctrine/data-fixtures               v1.1.1             Data Fixtures for all Doctrine Object Managers
  doctrine/dbal                        v2.5.2             Database Abstraction Layer
  doctrine/doctrine-bundle             1.6.1              Symfony DoctrineBundle
  doctrine/doctrine-cache-bundle       1.2.2              Symfony Bundle for Doctrine Cache
  doctrine/doctrine-fixtures-bundle    2.3.0              Symfony DoctrineFixturesBundle
  doctrine/doctrine-migrations-bundle  1.1.1              Symfony DoctrineMigrationsBundle
  doctrine/inflector                   v1.1.0             Common String Manipulations with regard to casing and singular/plural rules.
  doctrine/instantiator                1.0.5              A small, lightweight utility to instantiate objects in PHP without invoking their constructors
  doctrine/lexer                       v1.0.1             Base library for a lexer that can be used in Top-Down, Recursive Descent Parsers.
  doctrine/migrations                  v1.1.0             Database Schema migrations using Doctrine DBAL
  doctrine/orm                         v2.5.0             Object-Relational-Mapper for PHP             

这是一个测试实体:

<?php
// src/AppBundle/Entity/EduStructItem.php
namespace AppBundle\Entity;


use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;

/**
 * @ORM\Entity
 * @ORM\Table(name="test_edustructitemcollection")
 */
class EduStructItem
{
    /**
     * @ORM\Column(type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;


    /**
     * @var string
     * @Assert\NotBlank()
     * @ORM\Column(type="string", length=255, nullable=false)
     */
    private $title;


    /**
     * Preconditions are EduStructItems referencing to an EduStructItem.
     * For a single EduStructItem its empty (which have no subelements).
     * A join table holds the references of a main EduStructItem to its sub-EduStructItems (preconditions)
     *
     * @ORM\ManyToMany(targetEntity="EduStructItem",indexBy="id", cascade={"persist"})
     * @ORM\JoinTable(name="test_edustructitem_preconditioncollection",
     *     joinColumns={@ORM\JoinColumn(name="edustructitem_id", referencedColumnName="id")},
     *     inverseJoinColumns={@ORM\JoinColumn(name="edustructitem_precondition_id", referencedColumnName="id")}
     * )
     */
    public $preconditions;

    public function __construct()
    {
        $this->preconditions = new ArrayCollection();
    }

    public function getTitle()
    {
        return $this->title;
    }

    public function setTitle($title)
    {
        $this->title = $title;
    }


    public function getPreconditions()
    {
        return $this->preconditions;
    }

    public function addPrecondition(\AppBundle\Entity\EduStructItem $precondition)
    {
        $this->preconditions->add($precondition);
    }

    public function removePrecondition(\AppBundle\Entity\EduStructItem $precondition)
    {
        $this->preconditions->removeElement($precondition);
    }

}
?>

最后我总是遇到错误: [语义错误]第0行,第18列处'preconditions)'附近:错误:无效的PathExpression。应该使用StateFieldPathExpression或SingleValuedAssociationField。

现在我尝试了你的新解决方案:

$em = $this->getDoctrine()->getManager();
$query = $em->getRepository("AppBundle:EduStructItem")
    ->createQueryBuilder('e')
    ->addSelect('COUNT(e.preconditions) AS HIDDEN countpre')
    ->join('e.preconditions', 'precondition', Join::WITH)
    ->having('countpre = 1')
    ->getQuery();

并再次收到错误提示:[语义错误]第0行,第18列附近的'preconditions)':错误:无效的PathExpression。需要StateFieldPathExpression或SingleValuedAssociationField。如果我在HIDDEN之前写别名,我也会得到以下错误提示:[语义错误]第0行,第53列附近的'FROM AppBundle\Entity\EduStructItem':错误:未定义类'FROM'。请注意,这是一个自反关系,并且只有一个实体,但是有两个表格。正如您可以在我的实体注释中看到的那样,自关系保存在test_edustructitem_preconditioncollection表中,该表由Doctrine根据注释生成。我尝试了您最新的解决方案:
$qb = $em->getRepository("AppBundle:EduStructItem")
    ->createQueryBuilder('item');
$qb->addSelect('COUNT(precondition.id) AS countpre HIDDEN ')
    ->join('item.preconditions', 'precondition', Join::WITH)
    ->having('countpre = 1');

当我在HIDDEN之前使用countpre时,我总是会遇到以下错误: [语义错误] 第0行,第56列附近的'FROM AppBundle\Entity\EduStructItem':错误:未定义类'FROM'。
但是当我将countpre放在HIDDEN之后时:
$qb = $em->getRepository("AppBundle:EduStructItem")
            ->createQueryBuilder('item');
        $qb->addSelect('COUNT(precondition.id) AS HIDDEN countpre')
            ->join('item.preconditions', 'precondition', Join::WITH)
            ->having('countpre = 1');

我遇到了错误: 执行'SELECT t0_.id AS id_0, t0_.title AS title_1, COUNT(t1_.id) AS sclr_2 FROM test_edustructitemcollection t0_ INNER JOIN test_edustructitem_preconditioncollection t2_ ON t0_.id = t2_.edustructitem_id INNER JOIN test_edustructitemcollection t1_ ON t1_.id = t2_.edustructitem_precondition_id HAVING sclr_2 = 1'时出现异常: SQLSTATE [42S22, 207]: [Microsoft][ODBC Driver 11 for SQL Server][SQL Server]Ungültiger Spaltenname 'sclr_2'. 500 Internal Server Error - DBALException 1个相关的异常: SQLSrvException » 请注意,只有一个实体具有自引用,而且有这两个表:
USE [easylearndev4_rsc]
GO
/****** Object:  Table [dbo].[test_edustructitemcollection]    Script Date: 14.12.2015 09:31:55 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[test_edustructitemcollection](
    [id] [int] IDENTITY(1,1) NOT NULL,
    [title] [nvarchar](255) NOT NULL,
PRIMARY KEY CLUSTERED 
(
    [id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO

并且。
USE [easylearndev4_rsc]
GO
/****** Object:  Table [dbo].[test_edustructitem_preconditioncollection]    Script Date: 14.12.2015 09:32:21 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
REATE TABLE [dbo].[test_edustructitem_preconditioncollection](
    [edustructitem_id] [int] NOT NULL,
    [edustructitem_precondition_id] [int] NOT NULL,
PRIMARY KEY CLUSTERED 
(
    [edustructitem_id] ASC,
    [edustructitem_precondition_id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
ALTER TABLE [dbo].[test_edustructitem_preconditioncollection]  WITH CHECK ADD  CONSTRAINT [FK_34E716A81B7A6CEB] FOREIGN KEY([edustructitem_precondition_id])
REFERENCES [dbo].[test_edustructitemcollection] ([id])
GO
ALTER TABLE [dbo].[test_edustructitem_preconditioncollection] CHECK CONSTRAINT [FK_34E716A81B7A6CEB]
GO
ALTER TABLE [dbo].[test_edustructitem_preconditioncollection]  WITH CHECK ADD  CONSTRAINT [FK_34E716A85D864668] FOREIGN KEY([edustructitem_id])
REFERENCES [dbo].[test_edustructitemcollection] ([id])
GO
ALTER TABLE [dbo].[test_edustructitem_preconditioncollection] CHECK CONSTRAINT [FK_34E716A85D864668]
GO

最后,我自己找到了一种解决方法:

$em = $this->getDoctrine()->getManager();
$qb = $em->getRepository("AppBundle:EduStructItem")
    ->createQueryBuilder('e');
$qb->join('e.preconditions', 'p', Join::WITH)
    ->groupBy('e.id, e.title')
    ->having('count(p.id) = 1');

但我对此并不满意,因为ArrayCollection已经是聚合数据,为什么还要再次进行连接、计数和分组!这不应该是Doctrine的想法吧!有没有人知道更好的解决方案?

2个回答

2

试试这个:

$qb = $this->getDoctrine()->getManager()->getRepository("MyBundle:Groups")
    ->createQueryBuilder('g')
    ->having('count(g.members) = 3')
    ->orderBy('g.members', 'DESC')
; 

这个不起作用:[语义错误]第0行,第109列附近的“mebers”): 错误: 无效的PathExpression。应该是StateFieldPathExpression或SingleValuedAssociationField。ArrayCollection不能作为count()的参数接受! - Immanuel
可以让我们看一下你的实体,特别是映射吗? - scoolnico
我编辑了我的帖子并添加了一个示例代码。问题是我不能将count()应用于arraycollection - 我想知道你为什么可以! - Immanuel

1
$qb = $this->getDoctrine()->getManager()->getRepository"MyBundle:Groups")
    ->createQueryBuilder('g')
    ->addSelect('COUNT(g.members) AS count HIDDEN')
    ->having('count = 3')
    ->orderBy('count', 'DESC')
    ;

编辑

在您更新了问题之后,应该清楚地表明上述解决方案无法使用,因为您的情况是需要计算关系对象而不是单个字段。

$qb = $em->getRepository("AppBundle:EduStructItem") //Selfreferencing ManyToMany
         ->createQueryBuilder('item');
$qb->addSelect("COUNT(precondition.id) AS count HIDDEN")
   ->join('item.preconditions', 'precondition', Join::WITH)
   ->having('count = 3')
   ->orderBy('count');

这个不起作用:由于嵌套引号,$qb->addSelect('COUNT('g.members') AS count HIDDEN') 存在语法错误。我将其更改为 $qb->addSelect("COUNT('g.members') AS count HIDDEN") 但仍然导致以下错误消息:[语法错误]第0行,第101列:错误:期望字面量,得到'count'。 - Immanuel
请考虑更新的问题文本。现在有一个示例可用。 - Immanuel
@Immanuel,请查看更新后的答案。告诉我这是否解决了你的问题。 - stevenll
您的更新答案不起作用。请查看我的更新问题以查看结果。 - Immanuel
1
最终我自己找到了一个解决方法,但是我对它并不是很满意。请查看更新后的问题。 - Immanuel
显示剩余3条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接