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


wrapAsync = require './wrapAsync'

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

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

    @hasMany: (name, opts = {}) ->
      db.once 'modelsLoaded', =>
        that = @
        @relations ?= {}
        @relations.hasMany ?= {}


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

    @createIndexes: ->
      run(@table().indexList()).then (existed) =>
        tasks = for name, val of @indexes when name not in existed
          if _.isBoolean val
            run @table().indexCreate name
          else
            run @table().indexCreate name, val

        Promise.all(tasks).then =>
          run @table().indexWait()

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