Вопрос

I need to get a specific object from my collection Doctrine.

Currently, I have two entity (with ManyToMany bidirectional relationship):

  • Categoy
  • User

And in my User entity, I have a board property defined as an 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;
}

And in my Categories Entity, I have this:

/**
 * @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;
}

When I need to get all the categories in my database I process like this:

$user = $this->getUser();
$categories = $user->getCategories()
\Doctrine\Common\Util\Debug::dump($categories) // OK: Result is the categories belonging to the user

But now I want to retrieve only the category of the user with the category name "Sport". How do I do this? I have to use the QueryBuilder and does not pass directly through my object ?

Finaly, I just want to add a condition to my $user->getBoards()

Thank's for your help !

Это было полезно?

Решение 2

Finaly, I have create a method in my categoryRepositor, like this:

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

That work's fine and I use this method like this:

$em = $this->getDoctrine();
$category = $em->getRepository("WebsiteBundle:Category")
                ->findOneUserCategoryById(1, 5);

Другие советы

I will definitely go for the query builder, but i think you can achieve wat you want with filters, it will be kind of tricky but here is the doc hope it helps http://doctrine-orm.readthedocs.org/en/latest/reference/filters.html

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top