PhilWaldmann / openrecord

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

relations #50

Closed SampsonCrowley closed 7 years ago

SampsonCrowley commented 7 years ago

There is no documentation on how to actually retrieve a relationship.

for instance:

module.exports = function (){
  this
  .validatesUniquenessOf('athlete_id')
  .validatesUniquenessOf('email')
  .validatesFormatOf('email', /^[^@\s\;]+@[^@\s\;]+\.[^@\s\;]+$/)
  .belongsTo('athlete')
  .hasMany('accountsUsers')
  .hasMany('users', {through: 'accountUsers'})
  .hasMany('infokits')
  .hasMany('account_audits')
}

how would I retrieve the 'users' for the above model? how do I get the athlete?

PhilWaldmann commented 7 years ago

I'm currently working on getting the docs complete.

You could do the following:

Model.join('athlete') //for a left join - or use .leftJoin(), rightJoin(), .innerJoin() or .outerJoin()

if you just want to prefetch relational data, use .include().

The arguments for .join() and .include() could be a:

See includes-test.js

SampsonCrowley commented 7 years ago

so there's no method to fetch an association after the parent is loaded?

e.g. the example above model is 'Account' in the following (obviously unnecessary as is, but shows more of what i'm looking at) example:

Account.get(MY_ID).exec().then((account) => account.athlete.load())

or

Account.get(MY_ID).exec().then((account) => account.relations.athlete.load())
PhilWaldmann commented 7 years ago

With a has_many relation, you could do the following:

Account.get(MY_ID).exec()
.then((account) => account.athletes.exec())
.then(athletes => console.log(athletes))

This currently only works with has_many and belongsToMany, because the relation object (empty array) has all conditions at hand. It's a preconfigured query like Athlete.where({account_id: 1234}). belongs_to relations return null for a record that isn't prefetched.

I've some ideas to solve this problem. But this is a breaking change, so another thing to address in v2