Question

I'm trying to do a count on a table in a Symfony2 project where the records need to match a several values in one field. The SQL is something like this:

SELECT * FROM posts WHERE userid IN ('3,4,1') AND open = '1';

At the moment, I have this code:

        $group = '3,4,1';

        $activePosts = $dm->createQuery('
        SELECT COUNT(p.id)
        FROM AcmeBundle:Posts p
        WHERE p.userId IN (:user)
        AND mb.open = :active'
        )->setParameters(array(
            'user' => $group,
            'active' => '1'
        ));

        $actPost = $activePosts->getSingleScalarResult();

And it does retrieve records, but it ignores the last two values in the $group variable. So in this case, it's essentially running the query using the number "3" and doesn't bother using "4" or "1".

How can I replicate what I can do with the SQL query but in Symfony2?

Was it helpful?

Solution

You need to make $group as array in order to utilize IN() clause

$group = array('3','4','1');

$activePosts = $dm->createQuery('
        SELECT COUNT(p.id)
        FROM AcmeBundle:Posts p
        WHERE p.userId IN (:user)
        AND mb.open = :active'
        )->setParameters(array(
            'user' => $group,
            'active' => '1'
        ));

This is will result in WHERE p.userId IN ('3','4','1') and your current query is using it like WHERE p.userId IN ('3,4,1') which is wrong and it is searching for a string 3,4,1 not for individual ids

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top