我在两个实体之间有一个多对多关系:Books
<--> Account
如何在关联表上编写带有条件的 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
在你的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);