Home » Php » php – Count and group-by with Propel

php – Count and group-by with Propel

Posted by: admin July 12, 2020 Leave a comment


In Doctrine I can do:

public function getCount() 
        $q = $this->createQuery('q')
            ->addSelect('count(q.name) as count')
            ->orderBy('count DESC');

        return $q->execute();        

How can I do the same in Propel in Symfony 1.4?

How to&Answers:

Damned! It’s easier than that!

If you need to count result rows for a given query, you need to use the count() termination method, basically:


Read the following documentation section for more information: http://www.propelorm.org/documentation/03-basic-crud.html#query_termination_methods

If you want to add a count or nb extra column to your query which represent a SQL aggregate functions like COUNT or SUM, then you should use the withColumn() method:

$query = MyTableQuery::create()
    ->withColumn('COUNT(*)', 'Count')
    ->select(array('Name', 'Count'))

$results = $query->find();


try :

public function getCount() 
    $c = new Criteria();
    $c->addAsColumn('count', 'count(name)');
    return self::doCount($c);

There are some good snippets of info on propel queries here -> http://snippets.symfony-project.org/snippets/tagged/criteria/order_by/date


Something like this:

$myRows = MyTableQuery::create()->
    addAsColumn('count', 'COUNT(name)')->

I’m not sure about the GROUP BY – you may need an alias, or to re-specify the COUNT clause. Try it and see what works by experimentation :)

You really must use an auto-completing IDE to take advantage of Propel (and Doctrine for that matter) – your queries will be much easier to construct.

My usual reply would normally be like @ManseUK’s, i.e. based on the Criteria class – but that will be phased out when Propel 2 comes along, so it’s probably a good idea to get your code ready now.