0

使用此 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.

我做错了什么?

4

1 回答 1

0

DQL(据我所知)的学说(据我所知)中不提供子查询。你能写它查询生成器吗?

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

参考

于 2014-01-13T07:57:29.850 回答