doctrine 2 - query builder conditional queries... If statements?
Asked Answered
A

1

6

My query is doctirne 2. i have a status field in users, private or public. i want to be able to run this query and display all comments where status= public and private only if userid = current logged in user id(which i know, $loggerUserVarID)

  $q = $this->em->createQueryBuilder()
            ->select('c')
            ->from('\Entities\Comments', 'c')
            ->leftJoin('c.users', 'u')
            ->where('status = public')  ???  display all public comments but private if it belpongs to the logged in user.?
            ->setParameter(1, $loggerUserVarID)
            ->getQuery();

at the moment, i am using an if statement after i get thee results, is there a way to do an if statement inside this query?

Alkalinize answered 10/10, 2011 at 17:46 Comment(1)
Whats irritating: a comment has a users property - means multiple users are mapped to a comment? Hows that going to work? Cant a comment just have one owner (user)?Bulb
R
10

So, you want to return Comments "If status is 'public' or the ownerId is $loggedUserVarID", right?

Note that if $loggedUserVarID matches the owner, you don't really care about status.

Check out the querybuilder and dql docs. They explain pretty clearly how to put together complex where conditions.

What you probably want is something like:

$q = $this->em->createQueryBuilder()
            ->select('c')
            ->from('\Entities\Comments', 'c')
            ->join('c.users', 'u')
            ->where(
                $qb->expr()->orX(
                    $qb->expr()->eq('status','public'),
                    $qb->expr()->eq('u.id',$loggedInUser)
                )
           )
         ->setParameter(1, $loggerUserVarID)
         ->getQuery();
Rosenberry answered 11/10, 2011 at 2:14 Comment(1)
you can also so do like this: $ors = $qb->expr()->orX(); $ors->add($qb->expr()->like('firstName', $qb->expr()->literal("%john%"))); $ors->add($qb->expr()->like('lastName', $qb->expr()->literal("%john%"))); $qb->andWhere($ors);Antoineantoinetta

© 2022 - 2024 — McMap. All rights reserved.