vidigami / backbone-orm

A polystore ORM for Node.js and the browser
http://vidigami.github.io/backbone-orm
MIT License
238 stars 15 forks source link

Relations? #13

Closed marcelklehr closed 10 years ago

marcelklehr commented 10 years ago

Hello,

how would I work with relations between entities? E.g. I want all items that can be purchased in a certain store. How would I do that using backbone-orm?

thanks in advance

kmalakoff commented 10 years ago

It's the main purpose of an ORM so its covered:

class Project extends Backbone.Model
  urlRoot: 'mongodb://localhost:27017/projects'
  schema:
    tasks: -> ['hasMany', Task]
  sync: require('backbone-mongo').sync(Project)

class Task extends Backbone.Model
  urlRoot: 'mongodb://localhost:27017/tasks'
  schema:
    project: -> ['belongsTo', Project]
  sync: require('backbone-mongo').sync(Task)

The functions in the relationship are to handle cross-file module require ordering. Basically, they get lazily bound.

In your case:

class Store extends Backbone.Model
  urlRoot: 'mongodb://localhost:27017/stores'
  schema:
    purchases: -> ['hasMany', Purchase]
  sync: require('backbone-mongo').sync(Store)

class Purchase extends Backbone.Model
  urlRoot: 'mongodb://localhost:27017/purchases'
  schema:
    store: -> ['belongsTo', Store]
  sync: require('backbone-mongo').sync(Purchase)

You can swap out mongo for sql-variants using require('backbone-sql').sync(Purchase)