使用Zend Framework 2 / Doctrine 2进行DQL INNER JOIN

时间:2013-05-20 15:26:14

标签: doctrine-orm zend-framework2 dql

使用此SQL语句,我可以从所有用户获取最新消息:

SELECT  m1.*
FROM    message AS m1
INNER JOIN user
   AS u1
   ON m1.sender_id = u1.user_id
INNER JOIN (
   SELECT   sender_id,
   MAX(dateSent) MaxDate
   FROM     message
   WHERE receiver_id = 4
   GROUP BY sender_id
) AS m2
ON m1.sender_id = m2.sender_id
AND m1.datesent = m2.MaxDate;

这些是我的Zend Framework 2应用程序中的实体:

首先,我收到了消息。用户可以向其他用户发送消息。

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

/**
 * @ORM\ManyToOne(targetEntity="Application\Entities\User", inversedBy="messagesSent")
 * @ORM\JoinColumn(referencedColumnName="user_id")
 */
private $sender;

/**
 * @ORM\ManyToOne(targetEntity="Application\Entities\User", inversedBy="messagesReceived")
 * @ORM\JoinColumn(referencedColumnName="user_id")
 */
private $receiver;

/**
 * @ORM\Column(type="string", length=1024)
 */
private $message;

此处的用户实体:

/**
 * @ORM\Entity
 * @ORM\Table(name="user")
 */
class User
{
/**
 * @var int
 * @ORM\Id
 * @ORM\Column(type="integer")
 * @ORM\GeneratedValue(strategy="AUTO")
 */
protected $user_id;

尝试 SQL转换为DQL 并得到了这个:

SELECT  m1.*
FROM    Application\Entities\Message AS m1
INNER JOIN Application\Entities\User AS u1
    WITH m1.sender_id = u1.user_id
INNER JOIN (
    SELECT  sender_id,
    MAX(dateSent) MaxDate
    FROM    Application\Entities\Message
    WHERE receiver_id = 4
    GROUP BY sender_id
) AS m2
WITH m1.sender_id = m2.sender_id
AND m1.datesent = m2.MaxDate;

如果我执行它,我从Doctrine收到错误:

[Semantical Error] line 0, col 206 near '(
      ': Error: Class '(' is not defined.

我做错了什么?

1 个答案:

答案 0 :(得分:0)

在DQL(来自this)的学说(据我所知)中,子查询不可用。你能写出来query builder吗?

public function innerJoin($join, $alias = null, $conditionType = null, $condition = null);

请参阅Reference