Doctrine 2 Restricting Associations with DQL

被刻印的时光 ゝ 提交于 2019-12-01 12:27:51

问题


There seems to be an over sight in Doctrine 2.1 where it isn't easy to return a subset collection for an association.

http://www.doctrine-project.org/docs/orm/2.1/en/reference/limitations-and-known-issues.html#restricing-associations

The docs recommend to write a repository find method, which makes sense because that was the first thing I though of doing.

However without having a reference to the EntityManager within an Entity I can't see how you would retrieve the association's Repository and this seems to defeat the point of separating the Domain from the Database?

Is there a recommended strategy for this problem?

Here is my interpretation of their suggested solution.

class Category
{
    protected $id;
    protected $articles; // PesistentCollection
    protected $em; // The EntityManager from somewhere?

    public function getVisableArticles()
    {
        return $this->em->getRepository('Article')
                    ->getVisibleByCategory($this);
    }
}

回答1:


  1. Having entitymanager in an entity isn't a good thing in any case (inject your repository instead)
  2. Category isn't the only root for articles because it can't daterimne what articles you need, so you need a repository for articles.

What i would do:

class Category
{
    protected $id;
    protected $articles; // PesistentCollection

    public function getVisableArticles(IArticleRepository $articleRepository)
    {
        return $articleRepository->getVisibleByCategory($this);
    }
}

interface IArticleRepository
{
    function getVisibleByCategory(Category $category);
}

Your doctrine's repository would implement IArticleRepository and the class won't know anything about your data storage/doctrine.



来源:https://stackoverflow.com/questions/8240335/doctrine-2-restricting-associations-with-dql

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