I need to get number of rows from table as string. I execute this code:
$phql = "SELECT COUNT(*) FROM Model WHERE id = $this->id";
$count = $this->getModelsManager()->createQuery($phql)->execute();
Now $count
is Phalcon\Mvc\Model\Resultset\Complex
object. To get a proper result I need to do something like that:
$count[0]->{0}
In my opinion this is awful. Is there any other way to get this result?
Few solutions:
1) Use simple queries:
$count = $this->db->fetchOne('SELECT COUNT(*) AS total FROM products');
2) Model aggregations
$count = Products::count(
"area = 'Testing'"
);
More info and methods: https://docs.phalconphp.com/ar/3.2/db-models in section Generating Calculations
3) If you insist of using executeQuery()
you should add getFirst()
in order to get only one result. Similar to PDO's fetchOne()
.
$phql = "SELECT COUNT(*) AS total FROM Models\Products";
$count = $this->modelsManager->executeQuery($phql)->getFirst();