原则2:如何从专用状态表中获取最后一个状态

时间:2015-06-12 15:50:44

标签: php sql postgresql doctrine-orm

我有两个表:邮件和状态。

CREATE TABLE mail
(
  mail_id integer NOT NULL,
  mail_from character varying NOT NULL,
  mail_to character varying NOT NULL,
  subject character varying NOT NULL,
  text text,
  CONSTRAINT mail_pkey PRIMARY KEY (mail_id)
)

CREATE TABLE mail_status
(
  status_id integer NOT NULL,
  mail_id integer NOT NULL,
  code integer NOT NULL,
  CONSTRAINT mail_status_pkey PRIMARY KEY (status_id)
)

如何使用状态代码= 1的最后状态代码获取Doctrine 2所有邮件行。

E.g。 SQL:

SELECT mail.*
FROM mail
WHERE (SELECT code FROM mail_status WHERE mail_status.mail_id = mail.mail_id ORDER BY mail_status.status_id DESC LIMIT 1) = 1

1 个答案:

答案 0 :(得分:0)

在MailBundle / Entity / Repository / MailRepository中

public function findEmailsByStatusCode($code)
{ 
    $qb = $this->getEntityManager()->createQueryBuilder('mail');
    $qb
        ->select('mail')
        ->from('Path\MailBundle\Entity\Mail', 'mail')
        ->join('mail.statuses', 'mailStatus')
        ->where('mailStatus.code = :code'))
        ->orderBy('mailStatus.creationDate', 'DESC')
        ->groupBy('mail.mail_id')
        ->setParameter('code', $code)
    ;

    $query = $qb->getQuery();

    return $query->getResult();
}

然后从控制器中调用

$mailRepository = $this->getDoctrine()->getRepository('MailBundle:Mail');
$email = $mailRepository->findEmailsByStatusCode(1);