Phalcon - 在 PHQL 中获取计数结果

Phalcon - get result of count in PHQL

我需要从 table 中获取行数作为字符串。 我执行这段代码:

$phql  = "SELECT COUNT(*) FROM Model WHERE id = $this->id";
$count = $this->getModelsManager()->createQuery($phql)->execute();

现在 $countPhalcon\Mvc\Model\Resultset\Complex 对象。为了获得正确的结果,我需要做类似的事情:

$count[0]->{0}

在我看来这很糟糕。还有其他方法可以得到这个结果吗?

几个解决方案:

1) 使用简单查询:

$count = $this->db->fetchOne('SELECT COUNT(*) AS total FROM products');

2) 模型聚合

$count = Products::count(
    "area = 'Testing'"
);

更多信息和方法:https://docs.phalconphp.com/ar/3.2/db-models 部分 生成计算

3) 如果您坚持使用executeQuery(),您应该添加getFirst()以便只得到一个结果。类似于 PDO 的 fetchOne().

$phql  = "SELECT COUNT(*) AS total FROM Models\Products";
$count = $this->modelsManager->executeQuery($phql)->getFirst();