我需要从我的集合Doctrine中获得一个特定的对象。
目前,我有两个实体(具有ManyToMany双向关系):
- Categoy
- 用户
在我的用户实体中,我有一个定义为ArrayCollection:的板属性
/**
* @ORM'ManyToMany(targetEntity="'MyNamespace'WebsiteBundle'Entity'Category", inversedBy="users", cascade={"remove"})
* @ORM'JoinTable(name="user_categories")
*/
private $categories;
public function __construct()
{
parent::__construct();
$this->categories = new ArrayCollection();
}
/**
* get Categories
*
* @return 'Doctrine'Common'Collections'Collection
*/
public function getCategories()
{
return $this->categories;
}
在我的分类实体中,我有这样的:
/**
* @ORM'ManyToMany(targetEntity="'MyNamespace'UserBundle'Entity'User", mappedBy="categories")
* @Exclude
*/
private $users;
public function __construct()
{
$this->users = new ArrayCollection();
}
/**
* get Users
*
* @return 'Doctrine'Common'Collections'Collection
*/
public function getUsers()
{
return $this->users;
}
当我需要获取数据库中的所有类别时,我会这样处理:
$user = $this->getUser();
$categories = $user->getCategories()
'Doctrine'Common'Util'Debug::dump($categories) // OK: Result is the categories belonging to the user
但现在我只想检索类别名称为"Sport"的用户的类别。我该怎么做?我必须使用QueryBuilder,并且不直接通过我的对象?
最后,我只想在$user->getBoards()中添加一个条件
谢谢你的帮助!
我肯定会选择查询生成器,但我认为你可以通过过滤器实现你想要的wat,这会有点棘手,但这里是文档,希望它能有所帮助http://doctrine-orm.readthedocs.org/en/latest/reference/filters.html
最后,我在类别存储库中创建了一个方法,如下所示:
public function findOneUserCategoryById($user_id, $board_id)
{
$query = $this->getEntityManager()
->createQuery('
SELECT c FROM WebsiteBundle:Category c
JOIN c.users u
WHERE u.id = :user_id AND c.id = :category_id'
)
->setParameters(array(
'user_id' => $user_id,
'category_id' => $category_id)
);
try {
return $query->getSingleResult();
} catch ('Doctrine'ORM'NoResultException $e) {
return null;
}
}
这项工作很好,我使用这样的方法:
$em = $this->getDoctrine();
$category = $em->getRepository("WebsiteBundle:Category")
->findOneUserCategoryById(1, 5);