DataMapper


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) . '.';