简体   繁体   中英

cast_on_hydrate ignored when columns are specified in Query Builder

I've run into something quite specific in Phalcon and wondered if someone could take a look and advise if there is a fix?

In my bootstrap I have used ini_set() to set the value of cast_on_hydrate ini_set('phalcon.orm.cast_on_hydrate', 'on'); and I'm using Phalcon 3.4.0 on PHP 7.2.11.

If I use Model::find() style methods, cast_on_hydrate seems to be working fine. This changes when I use Query Builder though. Note that I'm using a multi-module style app with Model Namespacing enabled.

If I use Phalcon's Query Builder to create a simply query:

$di = \Phalcon\Di::getDefault();
$modelsManager = $di->getModelsManager();
$builder = $modelsManager
    ->createBuilder()
    ->from(['Jobs' => 'Jobs:Jobs']);
$results = $builder->getQuery()->execute();
var_dump($results[0]->id);

var_dump displays the result, correctly casted as an integer: int(87)

If I then add some columns into the mix:

// using same getModelsManager() as above
$builder = $modelsManager
    ->createBuilder()
    ->columns(['Jobs.id', 'Jobs.user_id'])
    ->from(['Jobs' => 'Jobs:Jobs']);
// getting results from $builder is same as above example

The output from var_dump is now string(2) "87"

My questions about this are:

  • Is this the expected behaviour, or is this a bug that I should report?

  • Are there any workarounds? eg I wondered if I used Phalcon\\Mvc\\Model\\MetaData\\Strategy\\Annotations whether that would make any difference

  • Can I pass the details of the selected columns to query builder somehow and force it to cast the results of the query in a certain way? I've seen Phalcon\\Mvc\\Model\\Query::setBindTypes() but this did not seem to work (see below)

For the final point here are some examples of what I've tried, which does not seem to work:

// using same $builder as above
$query = $builder->getQuery();
$query->setBindTypes([
    'Jobs.id' => \Phalcon\Db\Column::BIND_PARAM_INT,
    'Jobs:Jobs.id' => \Phalcon\Db\Column::BIND_PARAM_INT,
    'id' => \Phalcon\Db\Column::BIND_PARAM_INT,
]);
$results = $query->execute();
var_dump($results[0]->id); // string(2) "87"

I would really appreciate any suggestions or advice regarding the above. Thanks for your help in advance!

I got this working by editing my db service in the Dependency Injector and adding some options

'options'  => [
    PDO::ATTR_EMULATE_PREPARES   => false,
    PDO::ATTR_STRINGIFY_FETCHES  => false,
],

This goes just under your host, username, dbname, password etc when creating a new MySQL connection.

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