Doctrine:获取关注用户的帖子

Doctrine: Get followed users' posts

如何检索用户关注的用户的所有帖子,类似于社交媒体上的主页动态。

在 SQL 中非常简单,但是在 DQL 中这看起来像什么?

select * from post
join friends on friend_user_id = post.from_id
where user_id = :uid

我尝试了很多与此类似的方法,但无法奏效:

$this->getEntityManager()
    ->createQuery(
        'SELECT p
            FROM MyBundle:Post p
            JOIN MyBundle:User u WITH p.from IN u.myFriends
            WHERE u.id = :uid'
    )

我的用户实体 looks like in the documentation:

<?php
/** @Entity **/
class User
{
    // ...

    /**
     * @ManyToMany(targetEntity="User", mappedBy="myFriends")
     **/
    private $friendsWithMe;

    /**
     * @ManyToMany(targetEntity="User", inversedBy="friendsWithMe")
     * @JoinTable(name="friends",
     *      joinColumns={@JoinColumn(name="user_id", referencedColumnName="id")},
     *      inverseJoinColumns={@JoinColumn(name="friend_user_id", referencedColumnName="id")}
     *      )
     **/
    private $myFriends;

    public function __construct() {
        $this->friendsWithMe = new \Doctrine\Common\Collections\ArrayCollection();
        $this->myFriends = new \Doctrine\Common\Collections\ArrayCollection();
    }

    // ...
}

这是我的 Post 实体:

<?php
/** @Entity **/
class Post
{
    // ...

    /**
     * @ManyToOne(targetEntity="User")
     **/
    private $from;

    // ...
}

一个简单的工作 DQL 方法如下:

$dql   = "SELECT p FROM MyBundle:Post p
                   WHERE p.from in 
                    (SELECT u FROM MyBundle:User u JOIN u.friendsWithMe f where f = :user )";

$query = $em->createQuery($dql);
$query->setParameter(':user', $this->getUser());

希望对您有所帮助