5

I'm using DBAL in a Symfony project to access data in a Mysql database. When querying tables with boolean fields (created as tinyint) I get tinyint values in PHP but I would like to get booleans.

Somehow, I'd like to get the same mapping as using Doctrine directly.

I thought that the mapping conversion (from mysql to php) was already implemented in DBAL, but I'm not sure if it's suppose to work this way (this layer mapping values back).

I have tried registering a custom mapping like the following one, but no success:

    $this->conn->getDatabasePlatform()->registerDoctrineTypeMapping('tinyint', 'boolean'); 

    $sql = "
    SELECT se.survey_id, se.anonymous
      FROM survey_edition se
    ";
    $stmt = $this->conn->prepare($sql);
    $stmt->execute();

    $result = $stmt->fetch();

In this case 'anonymous' is a tinyint(1) field in Mysql, but I would like that $result['anonymous'] to be a boolean instead of an integer.

Do you know if it is possible to get boolean values in PHP from a Mysql query through Doctrine's DBAL?

Thanks.

Dmt
  • 193
  • 1
  • 10
  • Careful there, `tinyint` even `tinyint(1)` can hold values from -128 to 128 or 0 to 256 if signed. They're not meant to be used as booleans. If you want to get booleans then use Boolean(which in all fairness is still a tinyint) as the column type. With that said, if the return is either 1 or 0, the way php handles things, you could get away with doing `if($var)` or hack your way around this problem. – Andrei Jun 26 '15 at 12:29
  • Thanks for your answer. Yes, we could be doing if($var) as you commented, but I'm thinking something more general, like adding a mapping to the layer we're using to access data (Doctrine's DBAL layer in this case), so it can work in all cases and assuming that tinyint values will be mapped back to booleans. – Dmt Jun 26 '15 at 12:39

1 Answers1

1

Without using some ORM you cannot (as far as I know it) define model types.

Way to resolve this would be to iterate over the data and cast boolean values such as:

$item[$i]['foobar'] = (bool)$item[$i]['foobar']

But this is not even close to ideal solution.

Jovan Perovic
  • 19,846
  • 5
  • 44
  • 85
  • 1
    Ok, thanks. We had a look at the DBAL source code and it basically calls the PDO library when retrieving data and there's no option to hook up an event/method etc to transform the data when iterating the results. – Dmt Jun 26 '15 at 15:35