简体   繁体   中英

Automatic type cast in zend-db

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM