1

I'm using zend-db in combination with zend-expressive. I have a handler which selects all records from a database table and returns the results as JSON response:

public function handle(ServerRequestInterface $request) : ResponseInterface {
    $select = new Select();
    $select->from('person');
    $select->columns([
        'id',
        'name',
    ]);

    $sql = new Sql($this->dbAdapter);
    $statement = $sql->prepareStatementForSqlObject($select);
    $result = $statement->execute();

    $resultSet = new ResultSet();
    $resultSet->initialize($result);

    return new JsonResponse($resultSet->toArray());
}

What irritates me a little, that the response looks like this:

[{"id":"1","name":"tester"}]

The field "id" is of type INTEGER in my table (MySQL) and so I was expecting:

[{"id":1,"name":"tester"}]

Is there a way of an automatic type cast?

altralaser
  • 2,035
  • 5
  • 36
  • 55

1 Answers1

0

This is indeed possible, yet you have to do some preparations. The zdend-db comes with HydratingResultSet class, which is described here. You can deliver a prototype object, which will be instantiated as an effect of initializing a resultset. If you manage types properly in "setter" methods, and afterwards if you implement a \JsonSerializable interface to it, you can achieve your desired result.

yergo
  • 4,761
  • 2
  • 19
  • 41