加入多对多

时间:2018-01-26 22:37:31

标签: symfony doctrine-orm many-to-many

我与图书之间有多对多的关系< - >帐户

如何在关联表上用条件写DQL?

例如SQL:

SELECT books.*, account.id FROM books 
LEFT JOIN account_books ON books.id = account_books.books_id AND account_books.account_id = 17 
LEFT JOIN account ON account.id = account_books.account_id

1 个答案:

答案 0 :(得分:0)

在BooksRepository中,应该是那样的

public function getAccountBooks($accountId) {
    return $this->getEntityManager()
                ->createQueryBuilder()
                ->select("b.paramA", "b.paramB", "b.paramC", "acc.paramA")
                ->from('AppBundle:Books', 'b')
                ->leftJoin('AppBundle:AccountBooks', 'acb', 'WITH', 'b.id=acb.id')
                ->leftJoin('AppBundle:Account', 'acc', 'WITH', 'acc.id=acb.id')
                ->where("accountId = :accountId")
                ->setParameters(array(
                    new Parameter('accountId', $accountId),
                ))
                ->getQuery()
                ->getArrayResult();
}

请注意,DQL使用实体参数而不是SQL列名称

然后在action函数中:

$accountBooks=$em->getRepository('AppBundle:Books')
          ->getAccountBooks($accountId);