 
 
     @belongsTo: (name, opts = {}) ->
-      db.once 'modelsLoaded', =>
+      db.initModelsTasks.push =>
         @relations ?= {}
         @relations.belongsTo ?= {}
 


      async.each @[rel.name], save, cb

    @createIndexes: (cb) ->
      db.run @r().indexList(), (err, existed) =>
        indexes = ([name, val] for name, val of @indexes)
        createIndex = ([name, val], cb) =>
          return cb() if name in existed
          if typeOf(val) is 'boolean'
            db.run @r().indexCreate(name), cb
          else
            db.run @r().indexCreate(name, val), cb

        async.each indexes, createIndex, (err) =>
          db.run @r().indexWait(), cb

    @relatedQuery: (withRels, query)->
      query = query.map (item) =>


wrapAsync = require './wrapAsync'

module.exports = (db) ->
  Query = require('./Query')(db)
  {Promise, run, r} = db

  class Model extends EventEmitter
    isNewRecord: yes
    @primaryKey: 'id'

    @hasMany: (name, opts = {}) ->
      db.initModelsTasks.push =>
        that = @
        @relations ?= {}
        @relations.hasMany ?= {}
