Phalcon - 在 PHQL 中获取计数结果

Rob*_*n71 2 php phalcon

我需要从表中获取行数作为字符串。我执行此代码:

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

现在$count是Phalcon\Mvc\Model\Resultset\Complex对象。为了获得正确的结果,我需要做这样的事情:

$count[0]->{0}
Run Code Online (Sandbox Code Playgroud)

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

Nik*_*lov 5

几个解决方案:

1) 使用简单的查询:

$count = $this->db->fetchOne('SELECT COUNT(*) AS total FROM products');
Run Code Online (Sandbox Code Playgroud)

2) 模型聚合

$count = Products::count(
    "area = 'Testing'"
);
Run Code Online (Sandbox Code Playgroud)

更多信息和方法: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();
Run Code Online (Sandbox Code Playgroud)