gpt4 book ai didi

javascript - 创建具有关联外键的新模型实例/记录

转载 作者:行者123 更新时间:2023-12-03 22:36:24 28 4
gpt4 key购买 nike

我是 Sequelize 的新手并且遇到了一些语法问题。我制作了以下模型:

// User
sequelize.define('user', {
name: {
type: DataTypes.STRING,
allowNull: false,
},
});

// Type
sequelize.define('type', {
typeName: {
type: DataTypes.STRING,
allowNull: false,
},
});

我在它们之间创建了一个关联:
User.Type = User.belongsTo(Type, { foreignKey: { allowNull: false } })

并确认生成的 User 表具有对 typeId 的外键引用。

当我想创建一个新用户时,我还想传入一串“fan”或“band”,它们将是对填充 Type 表的两种类型之一的引用。我如何在我的 create 函数中传达这一点?
const createUser = (req, res) => {
const { name, type } = req.body;
User.create({
name,
include: [{
association: User.Type
}]
})
.then(() => console.log('success'))
.catch((err) => console.log(err));
}

最佳答案

您可以使用关联创建用户和类型。下面使用 "sequelize": "^5.21.3" 的示例

例如。
index.js :

import { DataTypes } from 'sequelize';
import { sequelize } from '../../db';

export const User = sequelize.define('user', {
name: {
type: DataTypes.STRING,
allowNull: false,
},
});

export const Type = sequelize.define('type', {
typeName: {
type: DataTypes.STRING,
allowNull: false,
},
});

User.Type = User.belongsTo(Type, { foreignKey: { allowNull: false } });

export const createUser = (req, res) => {
const { name, type } = req.body;
return User.create(
{
name,
type: { typeName: type },
},
{ include: [{ association: User.Type }] },
)
.then(() => console.log('success'))
.catch((err) => console.log(err));
};
index.test.js :

import { createUser, Type, User } from './';
import { sequelize } from '../../db';

describe('59849396', () => {
beforeAll(async () => {
await sequelize.sync({ force: true });
});
afterAll(async () => {
await sequelize.close();
});
it('should create user with type correctly', async () => {
const mReq = { body: { name: 'Tom', type: 'band' } };
const mRes = {};
await createUser(mReq, mRes);
const type = await Type.findOne({ where: { typeName: 'band' } });
const user = await User.findOne({ where: { name: 'Tom' } });
expect(type.typeName).toBe(mReq.body.type);
expect(user.typeId).toBe(type.id);
});
});

测试结果:

 PASS  src/examples/stackoverflow/59849396/index.test.js
59849396
✓ should create user with type correctly (74ms)

Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 2.253s, estimated 4s

运行测试后,检查数据库。

node-sequelize-examples=# select * from users;
id | name | createdAt | updatedAt | typeId
----+------+----------------------------+----------------------------+--------
1 | Tom | 2020-01-22 07:12:05.447+00 | 2020-01-22 07:12:05.447+00 | 1
(1 row)

node-sequelize-examples=# select * from types;
id | typeName | createdAt | updatedAt
----+----------+---------------------------+---------------------------
1 | band | 2020-01-22 07:12:05.45+00 | 2020-01-22 07:12:05.45+00
(1 row)

如您所见,我们还在创建用户“Tom”时创建了“band” type。这意味着 types 表也填充了数据行。

关于javascript - 创建具有关联外键的新模型实例/记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59849396/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com