문제

I am using fatfree framework with the cortex ORM plugin. I am trying to get the number of records matching a specific criteria. My code:

$group_qry = new \models\system\UserGroup;
$group_qry->load(array('type=?',$name));
echo $group_qry->count(); //always returns 3, i.e total number of records in table

Initially I was thinking that this maybe because the filtering wasn't working and it always fetched everything, but that is not the case, cause I verified it with

while(!$group_qry->dry()){
    echo '<br/>'.$group_qry->type;
    $group_qry->next();
}

So how do I get the number of records actually loaded after filtering?

도움이 되었습니까?

해결책

Yeah this part is confusing: the count() method actually executes a SELECT COUNT(*) statement. It takes the same arguments as the load() method, so in your case :

$group_qry->count(array('type=?',$name));

It is not exactly what you need, since it will execute a second SELECT, which will reduce performance.

What you need is to count the number of rows in the result array. Since this array is a protected variable, you'll need to create a dedicated function for that in the UserGroup class:

class UserGroup extends \DB\SQL\Mapper {
  function countResults() {
    return count($this->query);
  }
}

If you feel that it's a bit of overkill for such a simple need, you can file a request to ask for the framework to handle it. Sounds like a reasonable demand.

UPDATE:

It's now part of the framework. So calling $group_qry->loaded() will return the number of loaded records.

다른 팁

xfra35 is right, there was currently no method for just returning the loaded items, when using the mappers as active record. alternatively you can just count the collection:

$result = $group_qry->find(array('type=?',$name));
echo count($result); // gives you the number of all found results

in addition, i've just added the countResults method, like suggested. thx xfra35.

https://github.com/ikkez/F3-Sugar/commit/92fa18130892ab7d2303edc31d2b1f4bba70e881

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top