0
我的模型:Sequelize.js belongsToMany實例方法創建不工作?
'use strict';
module.exports = function(sequelize, DataTypes) {
var Entity;
return Entity = sequelize.define('Entity', {
name: {
type: DataTypes.STRING,
allowNull: false
}
}, {
classMethods: {
associate: function(models) {
return Entity.belongsToMany(models.User);
}
}
});
};
和
'use strict';
module.exports = function(sequelize, DataTypes) {
var User;
return User = sequelize.define('User', {
name: {
type: DataTypes.STRING,
allowNull: false
},
username: {
type: DataTypes.STRING,
allowNull: false,
unique: true
},
email: {
type: DataTypes.STRING,
allowNull: false,
unique: true,
validate: {
isEmail: true
}
},
password: {
type: DataTypes.STRING,
allowNull: false
},
status: {
type: DataTypes.ENUM('active', 'inactive'),
defaultValue: 'active'
}
}, {
instanceMethods: {
display: function() {
var user;
user = {
name: this.name,
email: this.email,
username: this.username,
active: this.active
};
return user;
}
}
}, {
classMethods: {
associate: function(models) {
return User.belongsToMany(models.Entity);
}
}
});
};
我想創建一個用戶,然後附加一個實體到該用戶,所以我做:
newUser = {
name: req.body.name,
email: req.body.email,
username: req.body.username,
password: req.body.password
};
global.db.User.create(newUser).then(function(dbUser) {
var newEntity;
newEntity = {
name: newUser.name + " Default Entity"
};
console.log(dbUser);
return dbUser.createEntity(newEntity);
}).then(function(dbEntity) {
return console.log(dbEntity);
});
,但我得到一個錯誤:[TypeError: Object [object SequelizeInstance] has no method 'createEntity']
這是使用Sequelize
v2.0.0-rc8
我在做什麼錯?
但'dbUser'確實存在。它創建在一行:'global.db.User.create(newUser).then(function(dbUser){'。而'belongsToMany'是新的,應該處理這個。 – Shamoon 2015-02-10 16:17:02
@Shamoon他試圖告訴你dbUser沒有'#createEntity()'方法,'createEntity()'方法被注入到你的模型中,這將是'User'。你的'dbUser'是模型的一個dao實例,它只有' #getEntity'和'#setEntity'方法 – Calvintwr 2015-02-14 06:54:54
'createEntity'實際上應該存在,':M'中的關聯支持'createAssociation' – 2015-02-16 11:02:04