Simplifying Queries: Using sum, count, etc in Propel

Simplifying Queries: Using sum, count, etc in Propel
$c->addSelectColumn('sum('.dbTimeBlockPeer::TOTAL.') as total');
$rs = dbTimeBlockPeer::doSelectRS($c);
while ($rs->next()) { $total = $rs->getInt(1); }
So, simply use addSelectColumn. You have to work with the ResultSet offcourse, since you won’t be able to populateObjects.
In this case you can simply use ‘1′ in getInt(column index), since we’re sure only one column is being fetched. Note that the index starts at 1 and not at 0.
Now, imagine a case where you are not sure what the index is (it could also change in the project’s life cycle). Then you can use, dbTimeBlockPeer::translateFieldName(dbTimeBlockPeer::TOTAL, BasePeer::TYPE_COLNAME, BasePeer::TYPE_NUM)), which will return the position of column ‘total’.
This needs no explanation, but I’ll give it anyway: translateFieldName accepts as first argument a string (source), the source type name and the destination type name. You can go and look in the basePeer which type you need.
basedbTimeBlockPeer (generated by Propel)
private static $fieldNames = array ( BasePeer::TYPE_PHPNAME => array ('Id', 'UserId', 'ProjectId', 'Ticketnr', 'Changeset', 'Description', 'TimeIn', 'TimeOut', 'Total', ), BasePeer::TYPE_COLNAME => array (dbTimeBlockPeer::ID, dbTimeBlockPeer::USER_ID, dbTimeBlockPeer::PROJECT_ID, dbTimeBlockPeer::TICKETNR, dbTimeBlockPeer::CHANGESET, dbTimeBlockPeer::DESCRIPTION, dbTimeBlockPeer::TIME_IN, dbTimeBlockPeer::TIME_OUT, dbTimeBlockPeer::TOTAL, ), BasePeer::TYPE_FIELDNAME => array ('id', 'user_id', 'project_id', 'ticketnr', 'changeset', 'description', 'time_in', 'time_out', 'total', ), BasePeer::TYPE_NUM => array (0, 1, 2, 3, 4, 5, 6, 7, 8, ) );

No comments:

Post a Comment