简体   繁体   中英

Doctrine 2 Restricting Associations with DQL

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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM