doctrine condition on associative table when joining many to many

China☆狼群 提交于 2019-12-24 23:05:16

问题


I have many to many relationship between Books <--> Account

How can i write DQL with condition on associative table?

for example 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:


In your BooksRepository, should be something like that

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();
}

Do note that DQL use entity parameters and not SQL columns name

And then in your action function:

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


来源:https://stackoverflow.com/questions/48470552/doctrine-condition-on-associative-table-when-joining-many-to-many

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!