簡體   English   中英

使用關聯的外鍵創建新的模型實例/記錄

[英]creating a new model instance/record with associated foreign keys

我是 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”,它們將是對填充類型表的兩種類型之一的引用。 我如何在我的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表也填充了數據行。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM