PhilWaldmann / openrecord

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

find_by #63

Closed amir-s closed 6 years ago

amir-s commented 6 years ago

Hello!

Awesome work! I love how consistent and simple the API is!

I think it worth having a Model.find_by({key: 'value'}) method like the find_by in ActiveRecord.

It is easier to write

const user = await User.find_by({email: 'a@b.c'});

comparing to

const user = (await User.where({email: 'a@b.c'}).limit(1)).pop();

Or maybe there is a similar API that I'm missing?

PhilWaldmann commented 6 years ago

Thanks Amir!

Currently there is no equivalent function to the ActiveRecord find_by. But you could easily create a scope.

e.g.

// in your model definition
this.scope('find_by_email', function(email){
  this.where({email}).singleResult()
})

singleResult is not yet documented, but on my todo list! It's a breaking change to version 1 - in V1 limit(1) would return a single record.

So your query would look like this:

const user = await User.find_by_email('a@b.c')

If you need a generic find_by method, it's better to write a plugin, so it's automatically available to all your models:

// plugins/find_by.js
exports.model = {
  find_by: function(condition){
    return this.where(conditions).singleResult()
  }
}
PhilWaldmann commented 6 years ago

Instead of singleResult You could also write first. It‘s an alias

amir-s commented 6 years ago

Amazing. Having it as a plugin is even better. keeping the core as minimal as possible.

Thanks for the explanation. I'm getting more familiar with openrecord as i'm trying to use it to replace sequelizejs in a project of mine.

The documentation needs a bit of work though. I'll try to prepare some PRs for the docs :)