How to use 'distinct' in zend db model
Using distinct:
public function countFollowers($user_id) { $select = $this->select() ->distinct() ->where('user_id = ?', $user_id); $rowset = $this->fetchAll($select); $rowCount = count($rowset); return $rowCount;}
EDIT: After edit in question to get count of followers of a user. You actually need to use group NOT distinct. I have tested the following query works to fetch the data to be count()ed,
SELECT * FROM
followers
WHERE user_id = 1 GROUP BY user_id, follower_id
I have not tested the code, but something like this should work:
public function countFollowers($user_id) { $select = $this->select() ->where('user_id = ?', $user_id) ->group(array('user_id', 'follower_id')); $rowset = $this->fetchAll($select); $rowCount = count($rowset); return $rowCount;}
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.
Retrieving all the rows simply to get a count strikes me as overkill.
You can do a count using something like this:
$select = $db->select();$select->from('testcount', new Zend_Db_Expr('COUNT(id)')) ->where('user_id = ?', $someUserId);return $db->fetchOne($select);