Search code examples
doctrine-ormdoctrinemany-to-manydql

Doctrine: Get followed users' posts


How can I retrieve all posts from users a user is following, similar to a home feed on social media.

It's pretty simple in SQL, but what does this look like in DQL?

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

I tried plenty of approaches similar to this, but couldn't get any to work:

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

My User entity 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();
    }

    // ...
}

And here my Post entity:

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

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

    // ...
}

Solution

  • A simple Working DQL Approach is the following:

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

    Hope this help