javascript - 如何在 Sequelize 中创建关联

标签 javascript node.js orm sequelize.js associations

我有两个与“belongsTo”关系关联的 Sequelize 模型。我想在创建用户时创建 user_sources 的实例,但我正在努力完成它。

模型用户:

const User = sequelize.define('user', {
    email: {
        type: Sequelize.STRING,
        allowNull: false,
        unique: true,
    },
    password: {
        type: Sequelize.STRING,
        allowNull: false
    }
}, {
    tableName: 'users'
})

模型用户来源:

const UserSources = sequelize.define('user_sources', {
    abcNews: {
        type: Sequelize.BOOLEAN,
    },
    bbcNews: {
        type: Sequelize.BOOLEAN,
    }
}, {
    tableName: 'user_sources'
})

UserSources.belongsTo(User)

两个模型均已初始化,并且表已在数据库中正确创建。 According to the Sequelize documentation I should be able to create both with association in a single query像这样:

User
    .create({
        email: user.email,
        password: user.password,
    }, {
        include: UserSources
    })

但是,仅创建了用户。表中未创建 user_sources 项。

不幸的是,文档仅显示了从子模型创建父模型的示例,而不是相反的方式。我尝试了几种不同的方法,例如使用 hasOne 关联、在 include 中添加模型/关联选项、将数据放入 create 方法等。但我觉得我没有正确理解这个概念。

如果有人能阐明我的问题,我将不胜感激。谢谢。

最佳答案

“Sequelize ”:“^5.21.3”。以下是为具有关联的 UserUserSources 模型创建数据记录的三种方法。此外,我们不断使用userIduser_sources表添加外键约束。

例如

index.js:

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

const User = sequelize.define(
  'user',
  {
    email: {
      type: Sequelize.STRING,
      allowNull: false,
      unique: true,
    },
    password: {
      type: Sequelize.STRING,
      allowNull: false,
    },
  },
  {
    tableName: 'users',
  },
);

const UserSources = sequelize.define(
  'user_source',
  {
    abcNews: {
      type: Sequelize.BOOLEAN,
    },
    bbcNews: {
      type: Sequelize.BOOLEAN,
    },
  },
  {
    tableName: 'user_sources',
  },
);

UserSources.belongsTo(User);

// User.UserSources = User.hasOne(UserSources);
// User.hasOne(UserSources);

(async function test() {
  try {
    await sequelize.sync({ force: true });
    // 1. User.UserSources = User.hasOne(UserSources);
    // await User.create(
    //   {
    //     email: 'example@gmail.com',
    //     password: '123',
    //     user_source: {
    //       abcNews: true,
    //       bbcNews: true,
    //     },
    //   },
    //   {
    //     include: [
    //       {
    //         association: User.UserSources,
    //       },
    //     ],
    //   },
    // );

    // 2. User.hasOne(UserSources);
    // await User.create(
    //   {
    //     email: 'example@gmail.com',
    //     password: '123',
    //     user_source: {
    //       abcNews: true,
    //       bbcNews: true,
    //     },
    //   },
    //   {
    //     include: [UserSources],
    //   },
    // );

    // 3. UserSources.belongsTo(User);
    await UserSources.create(
      {
        abcNews: true,
        bbcNews: true,
        user: {
          email: 'example@gmail.com',
          password: '123',
        },
      },
      {
        include: [User],
      },
    );
  } catch (error) {
    console.log(error);
  } finally {
    await sequelize.close();
  }
})();

执行上述代码后,查看数据库中的数据记录:

node-sequelize-examples=# select * from "users";
 id |       email       | password
----+-------------------+----------
  1 | example@gmail.com | 123
(1 row)

node-sequelize-examples=# select * from "user_sources";
 id | abcNews | bbcNews | userId
----+---------+---------+--------
  1 | t       | t       |      1
(1 row)

数据记录已按预期创建。

关于javascript - 如何在 Sequelize 中创建关联,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60330280/

相关文章:

javascript - 幻灯片 : How to jump to different slides with div ids?

javascript - 将上下文添加到无上下文 Javascript 回调

javascript - 执行 alt-tab 时 Alt keyup 丢失

Node.js 数据库按顺序查询

javascript - 调用router中的中间件函数

java - 数据完整性违规异常 : not-null property references a null or transient value

php - PHP/jQuery/JavaScript 中的免费 OCR 处理 API

node.js - 第一次失败后如何停止 async.queue?

java - Hibernate:如何使用同一个表(或实体)的两列(字段)创建约束

.net - 生成 LINQ to DB2?