So basically I want an array of integers from a query using fetchAllKeyed for the results. The field is an tinyint in the db so I would expect an indexed array of integers but I am getting an indexed array of strings.

Here is the database call:

$query = $this->connection
  ->select('database_name', 'db')
  ->fields('db', ['first_index', 'value'])
  ->condition('db.value', 0, '<>')
  ->condition('second_index', $array, 'IN')

$indexed_array_of_ints = $query->fetchAllKeyed();

I've tried to find other mentions of this issue and I haven't so maybe I'm just doing it wrong, I don't know.

I know that I can convert the values after the call, but I'm looking to make this operation as fast as possible so any help here would be greatly appreciated.

  • just follow document drupal.org/node/1251174 – MrD Sep 8 at 2:41
  • 1
    @MrD Sorry, but I don't see the answer in that document. Can you be more specific? – mcoatney Sep 8 at 3:06

The issue here is that PDO returns strings, even for integer columns. Drupal handles this issue by providing the Typed Data API, which provides data typing used within Drupal, rather than PHP-level data typing.

In the Drupal 8 paradigm, database queries are generally made to query entity IDs, which are then used to load entities. Data is then retrieved from the entity. The Entity API on the back end will handle the setting/getting of the fields on the entity. The fields on the entity will all be of a Typed Data API data type, providing a consistent method of dealing with data types on the Drupal level.

The method of retrieving IDs, and loading entities is done for the sake of efficiency, as entities are cached, and may be loaded from backends such as Redis, therefore being much faster than retrieving the entity data from the database. And because fields are typed, it gives a consistent API for dealing with various data types, that can also be extended to provide additional data types through contributed modules.

So the question here becomes about what you are trying to do, and how you are trying to do it. If you are working with data that you've been saving to the database yourself, then you can switch to the Drupal way, and create a custom entity type then use the Entity API to set/get the field data. Or, if you are retrieving data from the DB that Drupal has saved there, it likely belongs to an entity that you should be retrieving, rather than directly retrieving the field data.

  • Thanks, this is a really good explanation. I wish there was a simple way to override the db pdo settings, but I'll probably have to rewrite the table as an entity anyway if that's going to be the most efficient way to retrieve the data. – mcoatney Sep 8 at 10:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.