2016-01-04 53 views
0

我在我的sails.js應用程序中使用sails-hook-sequelizesails-hook-sequelize-blueprintsSequelize HasMany不工作

我有一個模型叫做Site

module.exports = { 

    attributes: { 
     id: { 
      type: Sequelize.INTEGER, 
      primaryKey: true, 
      autoIncrement: true 
     }, 
     name: { 
      type: Sequelize.STRING, 
      required: true 
     } 
    }, 
    associations: function() { 
     Site.hasMany(Templates, { 
      as: 'templates' 
     }); 
    } 
}; 

每個網站都有多個關聯的Templates

module.exports = { 

    attributes: { 
     id: { 
      type: Sequelize.INTEGER, 
      primaryKey: true, 
      autoIncrement: true 
     }, 
     name: { 
      type: Sequelize.STRING, 
      required: true 
     } 
    } 
}; 

我得到一個錯誤說

/user/myproject/node_modules/sails-hook-sequelize-blueprints/index.js:362 
       var alias = foreign.as || foreign.name || foreign; 
           ^

TypeError: Cannot read property 'as' of undefined 

任何想法可能是什麼呢?

回答

-1

如前所述,這是因爲您的變量'foreign'未定義,您嘗試讀取未定義的屬性。

0

你需要一個foreignKey添加到hasMany定義:

Site.hasMany(Templates, { 
     as: 'templates', 
     foreignKey: 'SiteId' 
    }); 

belongsTo協會添加到Templates模型定義:

Templates.belongsTo(Site) // this will add SiteId to the Templates table 

這是很好的做法是一致的命名也是 - 模型名稱應該是單數(Template而不是Templates),這些關係及其以下方法將更加自我解釋RY。 Sequelize將在多數情況下有意義(即你正在處理很多實例)。