续集-许多协会都有

时间:2019-08-18 16:48:14

标签: node.js postgresql sequelize.js

我定义了两个模型:

db / models / User.js

const Sequelize = require('sequelize');

module.exports = (sequelize, DataTypes) => {
  class User extends Sequelize.Model {}

  const config = {
    sequelize,
    modelName: 'user',
    underscored: true,
    paranoid: true,
  });

  User.init({
    first_name: {
      type: DataTypes.STRING,
    },
    last_name: {
      type: DataTypes.STRING,
    },
  }, config);

  return User;
};

db / models / Group.js

const Sequelize = require('sequelize');

module.exports = (sequelize, DataTypes) => {
  class Group extends Sequelize.Model {}

  const config = {
    sequelize,
    modelName: 'group',
    underscored: true,
    paranoid: true,
  });

  Group.init({
    name: {
      type: DataTypes.STRING,
      allowNull: false,
    },
  }, config);

  return Group;
};

我想在那时之间创建多对多关联(这样一个组可以有许多用户,并且一个用户可以属于许多组。这是我的db/index.js

db / index.js

const Sequelize = require('sequelize');
const Logger = require('../config/logger');
const { DB } = require('../config/vars');
const UserModel = require('./models/User');
const GroupModel = require('./models/Group');

const sequelize = new Sequelize(
  DB.name,
  DB.username,
  DB.password,
  {
    host: DB.host,
    dialect: 'postgres',
  },
);

const Models = {
  User: UserModel(sequelize, Sequelize),
  Group: GroupModel(sequelize, Sequelize),
};

const setup = async () => {
  // Associations
  Models.User.belongsToMany(Models.Group, {
    through: 'UserGroups',
    as: { singular: 'group', plural: 'groups' },
  });
  Models.Group.belongsToMany(Models.User, {
    through: 'UserGroups',
    as: { singuler: 'user', plural: 'users' },
  });
  await sequelize.sync({ force: true });
};

module.exports = {
  ...Models,
  setup,
  Seeders,
  Sequelize,
  sequelize,
};

当我执行User.findAll()时,对象中没有返回groups属性。我应该如何在这里正确建立多对多关系?

1 个答案:

答案 0 :(得分:0)

User.findAll()将默认返回其关联的模型,您需要像这样使用include

User.findAll({
    include : {
        model : Groups 
    }
})

SIMPLE GUIDE