Solved thread

This post is marked as solved. If you think the information contained on this thread must be part of the official documentation, please contribute submitting a pull request to its repository.

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:


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 ?

$categoryModel->getArticles(["active = 1"])->count();


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);
            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: