2012-04-15 47 views
3

我正在使用symfony2的admingenerator模块的doctrine orm,我无法执行涉及两个表的select count。 我真的很感激任何想法。提前感谢!学说orm计数1:n关系加入

这是QueryBuilder的表达:

class ListController extends BaseListController 
{ 
protected function getQuery() 
    { 
     $query = $this->getDoctrine() 
        ->getEntityManager() 
        ->createQueryBuilder() 
        ->select('q, count(f.fbid) AS no') 
        ->from('Shlomi\UsersBundle\Entity\users', 'q') 
        ->leftJoin('q.fbid' , 'f') 
        ->groupBy('q.fbid'); 


     $this->processSort($query); 
     $this->processFilters($query); 
       $this->processScopes($query); 

     return $query->getQuery(); 
    } 
} 

两个实体我用的是:

class Users 
{ 
    /** 
    * @var integer $id 
    * 
    * @ORM\Column(name="id", type="integer", nullable=false) 
    * @ORM\Id 
    * @ORM\GeneratedValue(strategy="IDENTITY") 
    */ 
    private $id; 

    /** 
    * @var bigint $fbid 
    * 
    * @ORM\OneToMany(targetEntity="Friendships", mappedBy ="fbid") 
    * @ORM\JoinColumns({ 
    * @ORM\JoinColumn(name="fbid", referencedColumnName="fbid") 
    * }) 
    */ 
    private $fbid; 
    .... 

class Friendships 
{ 
    /** 
    * @var integer $Id 
    * 
    * @ORM\Column(name="id", type="integer", nullable=false) 
    * @ORM\Id 
    * @ORM\GeneratedValue(strategy="IDENTITY") 
    */ 
    private $Id; 

    /** 
    * @var Users 
    * 
    * @ORM\ManyToOne(targetEntity="Users", inversedBy="fbid") 
    * @ORM\JoinColumns({ 
    * @ORM\JoinColumn(name="fbid", referencedColumnName="fbid") 
    * }) 
    */ 
    private $fbid; 
.... 

而在友谊协会注解有自动化由生成实体(包含来自Users.fbid的fbid的外键引用)生成的用户(1:n)中的注释已被手动插入,据我所知。

我试图再次编辑查询生成器和注释一遍又一遍,但最终我得到这个:

An exception has been thrown during the rendering of a template ("Catchable Fatal Error: Object of class Doctrine\ORM\PersistentCollection could not be converted to string in C:\xampp\htdocs\symfony2\app\cache\dev\twig\ea\85\2b678090e942db52cc01e3950dbc.php line 225") in Admingenerated/ShlomiUsersBundle/Resources/views/UsersList/index.html.twig at line 92.

感谢, 离子

+0

看来我完全误解了注释。 本页面包含设置关系的完整信息,但需要花费大量时间来了解它: [Associations](http://docs.doctrine-project.org/projects/doctrine-orm/en/2.0 .x/reference/association-mapping.html) – 2012-04-15 22:58:24

+0

作为ORM的工作原理,不需要统计sql语句中的记录,而是从ArrayCollection属性的对象中统计记录。 $查询= $这 - > getDoctrine() - > getEntityManager() - > createQueryBuilder() - >选择('Q,F ') - >从(' 施洛米\ UsersBundle \实体\用户, 'q') - > leftJoin('q.friends','f'); – 2012-04-15 23:03:20

+1

你能用'admingenerated/ShlomiUsersBundle/Resources/views/UsersList/index.html.twig'代码更新这个问题吗?至少代码在92行左右。 – Kosta 2012-04-16 08:36:16

回答

1

尝试:

$qb = $this->getDoctrine() 
       ->getEntityManager() 
       ->createQueryBuilder(); 
    $query = $qb->select('q', $qb->expr()->count('f.fbid')) 
       ->from('Shlomi\UsersBundle\Entity\users', 'q') 
       ->leftJoin('q.fbid' , 'f') 
       ->groupBy('q.fbid'); 

这创建querybuilder($ qb)然后形成查询的两步过程非常重要,因此您可以使用$ qb方法(如expr()和count())