【问题标题】:Doctrine: Get one object of my collection (relation ManyToMany bidireccional)原则:获取我收藏的一个对象(关系多对多双向)
【发布时间】:2014-05-23 10:50:07
【问题描述】:

我需要从我的收藏 Doctrine 中获取一个特定的对象。

目前,我有两个实体(具有多对多双向关系):

  • 类别
  • 用户

在我的用户实体中,我有一个板属性定义为 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

但现在我只想检索类别名称为“运动”的用户的类别。 我该怎么做呢?我必须使用 QueryBuilder 并且不直接通过我的对象?

最后,我只想为我的 $user->getBoards() 添加一个条件

感谢您的帮助!

【问题讨论】:

    标签: php symfony object doctrine-orm entity-relationship


    【解决方案1】:

    我肯定会选择查询生成器,但我认为你可以使用过滤器实现你想要的 wat,这会有点棘手,但这里是文档,希望对 http://doctrine-orm.readthedocs.org/en/latest/reference/filters.html

    有所帮助

    【讨论】:

    • 好的!我将尝试使用 queryBuilder。谢谢;)
    【解决方案2】:

    最后,我在 categoryRepositor 中创建了一个方法,如下所示:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-03-17
      • 2015-04-05
      • 2011-04-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多