Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count and group-by with Propel

In Doctrine I can do:

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

        return $q->execute();        
}

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

like image 716
Johan Dannenberg Avatar asked Mar 06 '12 13:03

Johan Dannenberg


2 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:

MyTableQuery::create()->count();

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'))
    ->groupByName()
    ->orderByCount()
    ;

$results = $query->find();
like image 197
William Durand Avatar answered Sep 18 '22 23:09

William Durand


try :

public function getCount() 
    $c = new Criteria();
    $c->addAsColumn('count', 'count(name)');
    $c->addDescendingOrderByColumn($c->getColumnForAs('count')); 
    $c->addGroupByColumn('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

like image 38
Manse Avatar answered Sep 20 '22 23:09

Manse