在 Sequelize 中创建具有关联的实例

编程入门 行业动态 更新时间:2024-10-24 06:24:54
本文介绍了在 Sequelize 中创建具有关联的实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

使用 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 中创建具有关联的实例

本文发布于:2023-10-28 08:31:42,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1536104.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:实例   Sequelize

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!