0

I have a table in a PostgreSQL database whose columns are snake_case formatted.
Is there a way to retrieve my Model attributes in camelCase ?

eg: I have a table user with two columns id_user (primary key) and last_name
When I execute a query like the basic one findByPK(), I would get the following result (parsed on JSON, for the example) : { idUser : "bar", lastName: "foo" } instead of { id_user : "bar", last_name: "foo" }

I tried to manage that using a custom projection with aliases but I faced a problem when formatting the primary key in camelCase (using unsetField/setField).

Bouss
  • 3
  • 4
  • Do you know alias? `SELECT id_user as idUser ...`. But if you want everything in PHP, it'll take a few steps. – Gabriel Heming May 12 '17 at 14:39
  • @GabrielHeming this will not work well because the flexible entity class hydrated after assumes fields are underscore spaced. – greg May 12 '17 at 14:42

1 Answers1

0

In case you just want to export entities AS JSON, here is a way:

Override the FlexibleEntity::extract() and camel case all the keys. You can also add your own jsonSerialize method (calling extract) and make your entities to implement the JsonSerializable interface.

The FlexibleEntity class does not know anything about database. It could be used for something else though. Hence it does not know how to fetch related data. The idea here is to make your SQL queries to fetch the data you want, they will be extracted as well.

If that is not what you want, you can code your own FlexibleContainer entity class (I have heard someone did that to store recursive result sets).

greg
  • 3,354
  • 1
  • 24
  • 35
  • Indeed I want to export entities as JSON. The problem with the 1st solution is that `fields()` is called in multiple core places, so that it breaks some other parts. With the 2nd solution, `jsonSerialize()` doesn't seem to be called. Just overriding `extract()` works with simple entities. I would like to build a more generic solution, taking into account complex entities with relations. Do you have an idea to manage that ? – Bouss May 12 '17 at 15:23
  • True, `fields` is called in the `IdentityMapper`. I am going to update my answer. – greg May 12 '17 at 15:34
  • 1
    Just override `FlexibleEntity::extract()` did the job. Thanks ! – Bouss May 15 '17 at 09:10
  • I unfortunately encountered side-effects overriding `extract()` : `insertOne()` query makes a call to `$entity->extract()`. I have to override it and call `$entity->fields()` instead. There should be different methods for different needs (projection, insertion) instead of the the same call to `extract()` in both cases, shouldn'it ? – Bouss May 15 '17 at 15:44
  • oh! I am going to check that asap. – greg May 15 '17 at 19:16