DataMapper OverZealous Edition


Count

Count has a different result depending on the object you use it on and whether you have setup any query clauses. If you use it directly on an object, it returns the total number of records of that object type, that you have in the database. For example, let's say we have 10 users:

// Create user object
$u = new User();

// Outputs: 10
echo $u->count();

Now, lets say you wanted to get a specific count of only active users, and we knew we only had 7 of them. You can use query clauses to help with this. For example:

// Create user object
$u = new User();

// Outputs: 7
echo $u->where('active', TRUE)->count();

Count behaves slightly differently when used on a related object, as the count will be based on the total number of related records. For example, let's say we wanted to see how many active Users were in the Moderator Group:

// Create user object
$u = new User();

// Create group object
$g = new Group();
$g->get_by_name('Moderator');

// Outputs: 2 out of 7 users are moderators.
echo $g->user->where('active', TRUE)->count() . ' out of ' . $u->where('active', TRUE)->count() . ' ' . plural($u) . ' are ' . plural($g) . '.';

Excluding IDs from the Count

If you want to count all objects except one or more IDs, count can accept an optional array of IDs to exclude.

Continuing from above, lets say that we want all active users, except user #1 and user #2:

// Create user object
$u = new User();

// We want to exclude these users from the result
$excluded_ids = array(1, 2);

// Outputs: 5
echo $u->where('active', TRUE)->count($excluded_ids);

This works even if ids in the list were not in the result set, so you can exclude users that may or may not be active.