使用 Sequelize,我创建了两个模型:User 和 Login.
Using Sequelize, I've created two models: User and Login.
用户可以有多个登录名,但一个登录名必须只有一个用户,这意味着没有用户 ID 无法保存登录名.
Users can have more than one Login, but a login must have exactly one user, which means a Login cannot be saved without a User ID.
我如何一举.create一个带有用户关联的登录名?
How do I .create a Login with a User association all in one swoop?
当前代码(无效)
// Set up the models var User = sequelize.define('User', {}); var Login = sequelize.define('Login', {}); Login.belongsTo(User, { onDelete: 'cascade', foreignKey: { field: 'userId', allowNull: false, } }); // Create the instances var user = User.create().then(function() { // THIS IS WHERE I WOULD LIKE TO SET THE ASSOCIATION var login = Login.create({ userId: user.get('id') }); )};以上导致SequelizeValidationError: notNull Violation: UserId cannot be null
推荐答案假设您在用户和登录名之间有正确的关联,您可以创建一个包含登录名的用户:
Assuming you have the right association between users and login, you can just create a user including a login:
User.create({ name: "name", Login: {...} },{ include: Login })您可以在此处找到更多信息:docs.sequelizejs/manual/tutorial/associations.html#creating-with-associations
you can find more information here: docs.sequelizejs/manual/tutorial/associations.html#creating-with-associations
更多推荐
在 Sequelize 中创建具有关联的实例
发布评论