2

I use symfony 1.4.12 with doctrine. I have sfGuardUser table; I can count all records like this:

 $count_user=Doctrine::getTable('sfGuardUser')->count();

I have field in table "created_at"; If it possible to count all users, that where created in current year? Thank you!

denys281
  • 2,004
  • 2
  • 19
  • 38

2 Answers2

3
$first_day_of_current_year = date('Y-m-d H:i:s', strtotime('1 january'));

$q = Doctrine_Query::create()
  ->select('COUNT(u.*)')
  ->from('sfGuardUser u')
  ->where('u.created_at > ?', $first_day_of_current_year);
$total = $q->execute(array(), Doctrine_Core::HYDRATE_NONE);
$total = $total[0][0];
Tom
  • 30,090
  • 27
  • 90
  • 124
  • 1
    you can do that even simpler by modifying where statement: `->where('YEAR(u.created_at) = ?', date('Y'))` – melekes Jul 31 '11 at 06:52
  • 1
    you can also use the Doctrine::HYDRATE_SINGLE_SCALAR hydration method to retrieve the value as a single entity, resulting in so you can skip the last line. – 4levels Aug 27 '12 at 12:58
1

There are various ways to get the count of a record collection. Doctrine automatically creates a count query for you when you call the ->count() function on a query object or Table instance.

If for instance you would like to know the total amount of users and the amount of users created in the current year, you could go about it as follows:

$query = Doctrine_Query::create()
  ->from('sfGuardUser');
// alternative query retrieval
// $query = sfGuardUserTable::getInstance()->createQuery();
// all users
$totalUsers = $query->count();
// users created this year
$query->where('YEAR(created_at) = ?', date('Y'));
$totalUsersThisYear = $query->count();
4levels
  • 3,134
  • 1
  • 23
  • 22