0

I have to entities that have ManyToMany relation with linking table. Like this:

class User
{

    /**
     * @ORM\ManyToMany(targetEntity="Post")
     * @ORM\JoinTable(name="favorite_posts",
     *      joinColumns={@ORM\JoinColumn(name="user_id", referencedColumnName="id")},
     *      inverseJoinColumns={@ORM\JoinColumn(name="post_id", referencedColumnName="id")}
     *      )
     **/
    private $favoritePosts;
}

class Post
{
    /**
     * @ORM\ManyToMany(targetEntity="User", mappedBy="favoritePosts")
     */
    private $usersInFavorite;
}

And I can get all user's favorite posts using a User entity object:

$favorites = $user->getFavoritesPosts();

But I have no idea how to get EXACTLY THE SAME result using DQL or Doctrine Query Builder. Under result i mean an array of POST entity objects.

4

1 回答 1

1

Based on this exemple

If you want to fetch it by dql,

$dql = "SELECT p FROM Posts p INNER JOIN p.$usersInFavorite u WHERE u= ?1";

$query = $entityManager->createQuery($dql)
                       ->setParameter(1, $user);
$favoritePosts = $query->getResult();

I tested it this time and i found the results as requested.

if you have the id of the user entity instead of the entity the same code will work with $user being the id of the user.

于 2013-02-25T23:15:07.630 回答