/** * Count the number of linked models for givent instances. * */ public function countRelation(Relation $relation, array $objects, array $localOptions = array()) { $lmClass = $relation->lm->class; $this->setRoot($lmClass); $lmAttributePrefix = ''; if ($relation instanceof Relation\ManyMany) { $reversed = $relation->reverse(); $lmClass::relation($reversed->name, $reversed); $lmAttributePrefix = $reversed->name . '/'; $relation = $reversed; } // Get CM join attributes values for each given objects. $cmValues = array(); foreach ($objects as $o) { $cmValues[] = $o->get($relation->getCmAttributes()); } $lmAttributes = $relation->getLmAttributes(); if ($lmAttributePrefix) { foreach ($lmAttributes as &$attr) { $attr = $lmAttributePrefix . $attr; } } $options['conditions'] = (array) $relation->conditions; $options = array_merge($options, $localOptions); $q = $this->newSelect(); $this->setOptions($options); $q->whereTuple($lmAttributes, $cmValues); if ($scope = $relation->getScope()) { $this->applyScopes($scope); } $pk = $lmClass::table()->getPrimaryKey(); return $this->count(DB::distinct($pk)); }