我在这里看了很多答案,这些答案与Doctrine 2.1中严重缺乏功能有关,这可能是OOP正确性超越关系理智的结果.
我有两个表,有多对一的关系,文章和成员.会员可以发表许多文章.拥有方的注释是
/** * @var \Member * @ORM\ManyToOne(targetEntity="Member") * @ORM\JoinColumns({ * @ORM\JoinColumn(name="member_id",referencedColumnName="id") * }) */ private $member;
SELECT * FROM mbr_article WHERE active = 1 AND member_id = 6 ORDER BY article_id DESC
我最终得到的是
$rep = $this->getDoctrine()->getRepository('SMWMemberBundle:Article'); $q = $rep->createQueryBuilder('a') ->leftJoin('a.member','m') ->where('m.id = ?1') ->andWhere('a.active = 1') ->orderBy('a.id','DESC') ->setParameter(1,$id) ->getQuery();
哪个产生了
SELECT m0_.id AS id0,m0_.active AS active1,m0_.update_time AS update_time2,m0_.content AS content3,m0_.member_id AS member_id4 FROM mbr_article m0_ LEFT JOIN mbr_member m1_ ON m0_.member_id = m1_.id WHERE m1_.id = ? AND m0_.active = 1 ORDER BY m0_.id DESC
哪个工作,可能不会慢很多,但不需要JOIN,因为我已经有了Member对象.当我以另一种方式尝试时,我得到的所有文章不仅仅是活跃的文章.
我已经看到像Can you get a foreign key from an object in Doctine2 without loading that object?那样使用getEntityIdentifier的响应,并提到2.2中的改进,我可以说是IDENTITY(成员).
在Doctrine 2.1中有没有合理的方法呢?增强是否允许在查询构建器中使用andWhere(‘IDENTITY(member)=?’)?
编辑:
感谢@Ocramius,– >其中(‘IDENTITY(a.member)=?1’)在Doctrine 2.2中有效
解决方法
IDENTITY适用于Doctrine 2.2中查询构建器生成的WHERE子句.
$q = $rep->createQueryBuilder('a') ->where('IDENTITY(a.member) = ?1') ->andWhere('a.active = 1') ->orderBy('a.id','DESC') ->setParameter(1,$id) ->getQuery();
SELECT m0_.id AS id0,m0_.member_id AS member_id4 FROM mbr_article m0_ WHERE m0_.member_id = ? AND m0_.active = 1 ORDER BY m0_.id DESC