Doctrine2使用WITH子句连接表

时间:2013-08-22 08:57:06

标签: symfony doctrine dql

我有一个User实体,以及一个通过外键链接到User的UserData实体。

User实体具有以下映射:

    /**
 * @ORM\OneToOne(targetEntity="UserData", cascade={"persist", "remove"})
 * @var integer
 */
protected $userData;

UserData有一个简单的ID字段:

    /**
 * @ORM\Id
 * @ORM\Column(type="integer")
 * @ORM\GeneratedValue(strategy="AUTO")
 * @var integer
 */
protected $id;

确定;我想检索一个UserData实体,其UserData的字段为'NIN',值为'A00000000';我正在尝试使用这个DQL查询:

SELECT u FROM eCommerceUserBundle:User u JOIN eCommerceUserBundle:UserData ud ON u.userData = ud.id WHERE ud.NIN = :NIN

但是我收到了这个错误:

  

预期的Doctrine \ ORM \ Query \ Lexer :: T_WITH,“开启”

所以......我试着退出ON子句,就像这样:

SELECT u FROM eCommerceUserBundle:User u JOIN eCommerceUserBundle:UserData ud WHERE ud.NIN = :NIN

现在问题是Doctrine正在进行的原始查询:

    SELECT 
  u0_.id AS id0, 
  u0_.email AS email1, 
  u0_.password AS password2, 
  u0_.created AS created3, 
  u0_.lastLogin AS lastLogin4, 
  u0_.confirmed AS confirmed5, 
  u0_.blocked AS blocked6, 
  u0_.particularData_id AS particularData_id7, 
  u0_.institutionalData_id AS institutionalData_id8, 
  u0_.administratorData_id AS administratorData_id9 
FROM 
  user u0_ 
  INNER JOIN userData u1_ ON (u1_.NIN = ?)

所以似乎Doctrine正在将我的WHERE子句推入ON子句...

我该怎么办?

1 个答案:

答案 0 :(得分:3)

DQL QUERY应该是这样的:

SELECT u, ud 
FROM eCommerceUserBundle:User u 
JOIN u.userData ud
WHERE ud.NIN = :NIN

您可以选择用户及其userData,也可以不从SELECT子句中删除ud - 尽管如此,将返回User个对象的数组,但是从头开始填写userData - 不选择它将首先在$user->getUserData()上向数据库启动新查询。