How to use 'distinct' in zend db model-Collection of common programming errors

You can specify mysql functions in the ‘from’ function that makes up select query function. To use the from function you need to pass the table name as the first parameter, however passing $this (your table model class) works fine.

public function countFollowers($user_id)
{
  $rowset = $this->fetchAll(
    $this->select()
    ->from($this, array('DISTINCT user_id'))
    ->where('user_id = ?', $user_id)
  );

  return count($rowset);
}

[edit]

Based on your edit, ‘group’ may also work for you:

public function countFollowers($user_id)
{
  $rowset = $this->fetchAll(
    $this->select()
    ->where('user_id = ?', $user_id)
    ->group('user_id')
  );

  return count($rowset);
}

This will group all matching user_id into one record. So if a user is found, it will return 1, else 0.

Originally posted 2013-11-10 00:16:01.