PhilWaldmann / openrecord

Make ORMs great again!
https://openrecord.js.org
MIT License
486 stars 38 forks source link

How to initialize records from raw rows? #93

Closed arthurfranca closed 4 years ago

arthurfranca commented 5 years ago

Was looking at the code but couldn't figure out a good way of transforming the result set from knex/Model.raw(query).then(result => result.rows) into regular OpenRecord record objects.

The important thing is that i can't just do new Model(json), because i dont want a future .save() or .update() to end up creating new records on database, but just updating them (if primary keys are present).

Best i could do was the following:

const records = await Model.raw('...')
  .then(result => result.rows)
  .then(rows => rows.map(r => {
    r = new Model(r)
    r.__exists = true
    return r
  }))

But i'm afraid of letting my code rely on __exists which is an internal property.

Is there a recommended way of doing it?

PhilWaldmann commented 5 years ago

At the moment there is no easy way to do this. But instead of __exists = true use _exists().

arthurfranca commented 5 years ago

Thx, _exists() works. Just setting __exists = true seems to keep object.changes with many entries so that it later updates many unwanted properties.

edit: For those that might have same issue, I would like to add that doing Model.where({ id: rows.map(r => r.id) }) would lose row ordering