We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

count related models with parameters

Having a category model and an article model, i will count the total numbers of article within a category like this:

$categoryModel->getArticles()->count();

But if i want to count only the active articles i can not do it ?

$categoryModel->getArticles()->count("active = 1"); // not working
$categoryModel->getArticles()->count(array("active = 1")); // not working

I have tried to create a custom count() method in Articles model:

public function countActive()
{
    return parent::count(array("active = 1"));
}

But, countActive is never called because $categoryModel->getArticles() is an instance of Phalcon\Mvc\Model\Resultset\Simple

Any thoughts ?



8.6k
Accepted
answer
$categoryModel->getArticles(["active = 1"])->count();


51.1k

Yes. Thanks ! Cheers !

Sorry for bumping an old thread, but it's highly ranked based on the keywords when people search for this. For a less SQL intensive way to count you can add this method to your base class/model.

    public function countRelated($alias, $arguments = null)
    {
        $relation = $className = $manager = null;

        $className = get_class($this);
        $manager = $this->getModelsManager();
        $relation = $manager->getRelationByAlias($className, $alias);
        if(!is_object($relation))
            throw new Exception("There is no defined relations for the model '" . $className . "' using alias '" . $alias . "'");

        return call_user_func_array([$manager, 'getRelationRecords'], [$relation, 'count', $this, $arguments]);
    }

It's based off the 'getRelated' method: https://github.com/phalcon/cphalcon/blob/efe49ef795d5a3e3d867cfd3ce8f8f69317e8152/phalcon/mvc/model.zep#L3845