问题
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)
- 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