2015-12-09 27 views
6

Symfony2.8Doctrine 2.5を使用して、私はDoctrine ORMクエリで、arraycollectionが正確に3つの要素を含むすべてのデータセットをフィルタリングします。doctrine ORM count arraycollection where条件

$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前提条件のコレクションが含まれていたArrayCollectionです。

最後に、3つの前提条件を持つすべての結果を得たいと考えています。 さらに、配列コレクションの値の数で注文することもできます(order by Count(e.preconditions)など)。

別のバンドルを使用しているため、私は2.5.2から2.5.0にドクトリンを格下げました。私は、これは私の問題の原因であるが、ここでは完全を期すために、私の作曲家のショーの教義の一部であるとは思わない:

<?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); 
    } 

} 
?> 

:ここ

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    

は、テストエンティティであります最後に私はいつもエラーを受け取ります: [意味的エラー]行0、列18の '前提条件'の近くにあります:エラー:無効な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(); 

とget: [意味論的エラー]行0、列18の近くに '前提条件)':エラー:無効なPathExpressionを

は今、私はあなたの新しいソリューションを試してみました。 StateFieldPathExpressionまたはSingleValuedAssociationFieldが必要です。 Wenn私はHIDDENの前にエイリアスを書く:[意味的なエラー]行0、col 53 'FROM AppBundle \ Entity \ EduStructItem'の近く:エラー:クラス 'FROM'は定義されていません。それは自己反映関係であり、エンティティは1つだけですが、2つのテーブルがあるとします。私のエンティティのAnnotationでわかるように、自己関係は、注釈のためにdoctrineによって生成されたtest_edustructitem_preconditioncollection - テーブルに保存されます。

私はあなたの最新のソリューションを試みた: [意味論的エラー]行0、 'AppBundle \エンティティ\ EduStructItemから' COL 56近い:エラー私はオールウェイズこのエラーが出るHIDDEN前countpreたら

$qb = $em->getRepository("AppBundle:EduStructItem") 
    ->createQueryBuilder('item'); 
$qb->addSelect('COUNT(precondition.id) AS countpre HIDDEN ') 
    ->join('item.preconditions', 'precondition', Join::WITH) 
    ->having('countpre = 1'); 

を: 'FROM'クラスが定義されていません。

しかしwhenn、私はHIDDEN後countpreを置く:

$qb = $em->getRepository("AppBundle:EduStructItem") 
      ->createQueryBuilder('item'); 
     $qb->addSelect('COUNT(precondition.id) AS HIDDEN countpre') 
      ->join('item.preconditions', 'precondition', Join::WITH) 
      ->having('countpre = 1'); 

私はエラーを取得:ID_0、TITLE_1 AS t0_.title、COUNT(t1_.id)AS t0_.id SELECT」実行中に 例外が発生しました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' t0_ test_edustructitemcollection FROM sclr_2 AS:

SQLSTATE [42S22、207]:[マイクロソフト] [ ODBCドライバ11(SQL Server用)] [SQL Server]UngültigerSpaltenname 'sclr_2 '

500内部サーバーエラー - DBALException

1リンクされた例外:SQLSrvException»

1つのエンティティのみがselfreferenceであり、これら二つのテーブルがあることを考えてみてください:

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 

最後に、自分でラウンド:ArrayCollectionのはすでに私が参加すべき理由データを集計しているため

$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'); 

しかし、私はこれで非常に満足していないが、再びによりカウントおよびグループ! これはDoctrineのアイデアではありません! もっと良い解決方法を知っている人はいますか?

答えて

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

EDIT

あなたの質問を更新した後、あなたのケースでは、単一のフィールドの関係オブジェクトをカウントしていないする必要があるため、上記のソリューションが動作しないことを明確にする必要があります。

$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'); 
+0

を: $ QB-> addSelect( 'COUNT(' g.members ')のカウントHIDDEN AS')が原因に構文エラーがありますネストされた引用符。私はそれを$ qb-> addSelect( "COUNT( 'g.members')AS count HIDDEN ')に変更しますが、このエラーメッセージが表示されます:[構文エラー] ' – Immanuel

+0

に更新されたコードがあります。エラー: [意味的なエラー]行0、列101の'カウント= 3 'に近い:エラー:'カウント 'が定義されていません。隠された値はwhere条件ではアクセスできないと思われます。 – Immanuel

+0

「where」条件に「having」があります。私はこのコードを既に多くのプロジェクトで使用しています。たぶんあなたの文脈には何か違うものがあります。 – stevenll

2

このお試しください:これは動作しません

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

これは機能しません: [意味的なエラー]行0、コルク109 near mebers) ':エラー:無効なPathExpression。 StateFieldPathExpressionまたはSingleValuedAssociationFieldが必要です。 arraycollectionはcount()の引数として認識されません! – Immanuel

+0

あなたのエンティティ、さらには特に地図が表示されることがありますか? – scoolnico

+0

あなたはタイプミスがあります:* mebers *。それはエラー – stevenll