0

I have two entities (there is no relation between the two entities): A: Relation and B: Post. I get every post from the current user to display them on the homepage with this request:

public function getPostsCurrentUser($currentUser)
{
    $qb = $this->createQueryBuilder('p');
    $qb->where('p.member = :member')
        ->setParameters(['member' => $currentUser])
        ->orderBy('p.created', 'DESC');

    return $qb->getQuery()->getResult();
}

In the example "A: Relation" the user 2 follow the user 1. When a user follow an other user, I would like to also display on the homepage every post of users that the current user are following. I don't see how to create this request. Can anybody help me ?

Thanks

Matthieu
  • 1
  • 1

1 Answers1

0

In the sense of http://sqlfiddle.com/#!9/c5a0bf/2, I would suggest something like the following which uses a subquery to select the ids of all followed users:

class PostRepository {
    public function getPostsOfUser($id) {
        $query = $this->getEntityManager()->createQuery(
            "SELECT p.content
             FROM AppBundle:Post p
             WHERE p.member = :id
             OR p.memberId IN (
                 SELECT r.friend
                 FROM AppBundle:Relation r
                 WHERE r.user = :id
             )
             ORDER BY p.created DESC"
        );

        return $query->setParameter('id', $id)
                     ->getResult();
    }
}
chrisp
  • 569
  • 4
  • 24
  • Hello chrisp, thanks for your answer. With this request I have a syntax problem in my IDE. I tried your request directly in phpmyadmin guessing that the $id attribut is the current User and that works. I didn't understand why you used the $id and $user, can you please explain it to me ? sorry I'm a beginner with symfony. – Matthieu Jul 31 '16 at 09:56
  • I think that's just mistype as $user variable does not exist in the given code sample. it should be $id instead of $user. – sanis Jul 31 '16 at 10:21
  • My mistake, $user is a typo. Fixed. – chrisp Jul 31 '16 at 13:59
  • @chrisp thanks. Is it possible to integrate the sub query in my first request example ? – Matthieu Jul 31 '16 at 15:13
  • @Matthieu You mean using the query builder? It's not that much different. There are plenty of examples out there. For example this one: http://stackoverflow.com/a/6638146/3857641 – chrisp Jul 31 '16 at 18:30
  • @chrisp yes I want to use the query builder. I will have a look at this. thanks for your help – Matthieu Jul 31 '16 at 18:37