Функция добавления Sequelize многие ко многим не работает - PullRequest
0 голосов
/ 14 марта 2020

пакет. json

"express": "^ 4.17.1", "pg": "^ 7.17.1", "pg- hstore ":" ^ 2.3.3 "," sequelize ":" ^ 5.21.3 ",

Существует две модели:

// User
const User = seq.define('user', {
  id: {
    type: Sequelize.INTEGER,
    autoIncrement: true,
    primaryKey: true,
    allowNull: false
  },
  login: {
    type: Sequelize.STRING,
    allowNull: false
  },
  password: {
    type: Sequelize.STRING,
    allowNull: false
  },
  age: {
    type: Sequelize.INTEGER
  },
  isDeselected: {
    type: Sequelize.BOOLEAN
  }
}, { timestamps: false });

export default User;

// Group
const Group = seq.define('group', {
  id: {
    type: Sequelize.INTEGER,
    autoIncrement: true,
    primaryKey: true
  },
  name: {
    type: Sequelize.STRING,
    allowNull: false
  },
  permissions: {
    type: Sequelize.ARRAY
  }
}, { timestamps: false });

export default Group;

Есть группа для ассоциации:

import Group from './group';
import User from './user';

const UserGroup = seq.define('UserGroup');

Group.belongsToMany(User, { through: UserGroup });
User.belongsToMany(Group, { through: UserGroup });

seq.sync({ force:true }).then(() => { console.log("Tables have been created"); }).catch(err=>console.log(err));

И способ добавления пользователя в группу:

UserModel.findOne({ where: { id: userIds } })
      .then((user) => {
        if (!user) { return; }
        GroupModel.findOne({ where: { id: groupId } })
          .then((group) => {
            if (!group) return;
            user.addGroup(group);
          });

Есть ошибка во время выполнения:

необработанное отклонение TypeError: user.addGroup не является функцией

1 Ответ

0 голосов
/ 16 марта 2020

должно работать. Вот рабочий пример:

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

const User = seq.define(
  'user',
  {
    id: {
      type: Sequelize.INTEGER,
      autoIncrement: true,
      primaryKey: true,
      allowNull: false,
    },
    login: {
      type: Sequelize.STRING,
      allowNull: false,
    },
    password: {
      type: Sequelize.STRING,
      allowNull: false,
    },
    age: {
      type: Sequelize.INTEGER,
    },
    isDeselected: {
      type: Sequelize.BOOLEAN,
    },
  },
  { timestamps: false },
);

const Group = seq.define(
  'group',
  {
    id: {
      type: Sequelize.INTEGER,
      autoIncrement: true,
      primaryKey: true,
    },
    name: {
      type: Sequelize.STRING,
      allowNull: false,
    },
    permissions: {
      type: Sequelize.ARRAY(Sequelize.STRING),
    },
  },
  { timestamps: false },
);

const UserGroup = seq.define('UserGroup', {});

Group.belongsToMany(User, { through: UserGroup });
User.belongsToMany(Group, { through: UserGroup });

(async function test() {
  try {
    await seq.sync({ force: true });
    // seed
    await User.bulkCreate(
      [
        { login: 'a', password: '123', groups: [{ name: 'group a' }, { name: 'group b' }] },
        { login: 'b', password: '321', groups: [{ name: 'group c' }, { name: 'group d' }] },
      ],
      { include: [Group] },
    );

    // test
    const userIds = [1, 2];
    const groupId = 3;
    const user = await User.findOne({ where: { id: userIds } });
    const group = await Group.findOne({ where: { id: groupId } });
    const result = await user.addGroup(group);
    console.log(result);
  } catch (error) {
    console.log(error);
  } finally {
    await seq.close();
  }
})();

Результат выполнения и сгенерированные SQL:

Executing (default): DROP TABLE IF EXISTS "UserGroup" CASCADE;
Executing (default): DROP TABLE IF EXISTS "group" CASCADE;
Executing (default): DROP TABLE IF EXISTS "user" CASCADE;
Executing (default): DROP TABLE IF EXISTS "user" CASCADE;
Executing (default): CREATE TABLE IF NOT EXISTS "user" ("id"   SERIAL , "login" VARCHAR(255) NOT NULL, "password" VARCHAR(255) NOT NULL, "age" INTEGER, "isDeselected" BOOLEAN, PRIMARY KEY ("id"));
Executing (default): SELECT i.relname AS name, ix.indisprimary AS primary, ix.indisunique AS unique, ix.indkey AS indkey, array_agg(a.attnum) as column_indexes, array_agg(a.attname) AS column_names, pg_get_indexdef(ix.indexrelid) AS definition FROM pg_class t, pg_class i, pg_index ix, pg_attribute a WHERE t.oid = ix.indrelid AND i.oid = ix.indexrelid AND a.attrelid = t.oid AND t.relkind = 'r' and t.relname = 'user' GROUP BY i.relname, ix.indexrelid, ix.indisprimary, ix.indisunique, ix.indkey ORDER BY i.relname;
Executing (default): DROP TABLE IF EXISTS "group" CASCADE;
Executing (default): CREATE TABLE IF NOT EXISTS "group" ("id"  SERIAL , "name" VARCHAR(255) NOT NULL, "permissions" VARCHAR(255)[], PRIMARY KEY ("id"));
Executing (default): SELECT i.relname AS name, ix.indisprimary AS primary, ix.indisunique AS unique, ix.indkey AS indkey, array_agg(a.attnum) as column_indexes, array_agg(a.attname) AS column_names, pg_get_indexdef(ix.indexrelid) AS definition FROM pg_class t, pg_class i, pg_index ix, pg_attribute a WHERE t.oid = ix.indrelid AND i.oid = ix.indexrelid AND a.attrelid = t.oid AND t.relkind = 'r' and t.relname = 'group' GROUP BY i.relname, ix.indexrelid, ix.indisprimary, ix.indisunique, ix.indkey ORDER BY i.relname;
Executing (default): DROP TABLE IF EXISTS "UserGroup" CASCADE;
Executing (default): CREATE TABLE IF NOT EXISTS "UserGroup" ("groupId" INTEGER  REFERENCES "group" ("id") ON DELETE CASCADE ON UPDATE CASCADE, "userId" INTEGER  REFERENCES "user" ("id") ON DELETE CASCADE ON UPDATE CASCADE, PRIMARY KEY ("groupId","userId"));
Executing (default): SELECT i.relname AS name, ix.indisprimary AS primary, ix.indisunique AS unique, ix.indkey AS indkey, array_agg(a.attnum) as column_indexes, array_agg(a.attname) AS column_names, pg_get_indexdef(ix.indexrelid) AS definition FROM pg_class t, pg_class i, pg_index ix, pg_attribute a WHERE t.oid = ix.indrelid AND i.oid = ix.indexrelid AND a.attrelid = t.oid AND t.relkind = 'r' and t.relname = 'UserGroup' GROUP BY i.relname, ix.indexrelid, ix.indisprimary, ix.indisunique, ix.indkey ORDER BY i.relname;
Executing (default): INSERT INTO "user" ("id","login","password") VALUES (DEFAULT,'a','123'),(DEFAULT,'b','321') RETURNING *;
Executing (default): INSERT INTO "group" ("id","name") VALUES (DEFAULT,'group a'),(DEFAULT,'group b'),(DEFAULT,'group c'),(DEFAULT,'group d') RETURNING *;
Executing (default): INSERT INTO "UserGroup" ("groupId","userId") VALUES (1,1),(2,1),(3,2),(4,2) RETURNING *;
Executing (default): SELECT "id", "login", "password", "age", "isDeselected" FROM "user" AS "user" WHERE "user"."id" IN (1, 2) LIMIT 1;
Executing (default): SELECT "id", "name", "permissions" FROM "group" AS "group" WHERE "group"."id" = 3;
Executing (default): SELECT "groupId", "userId" FROM "UserGroup" AS "UserGroup" WHERE "UserGroup"."userId" = 1 AND "UserGroup"."groupId" IN (3);
Executing (default): INSERT INTO "UserGroup" ("groupId","userId") VALUES (3,1) RETURNING *;
[ UserGroup {
    dataValues: { userId: 1, groupId: 3 },
    _previousDataValues: { userId: 1, groupId: 3 },
    _changed: { userId: false, groupId: false },
    _modelOptions:
     { timestamps: false,
       validate: {},
       freezeTableName: true,
       underscored: false,
       paranoid: false,
       rejectOnEmpty: false,
       whereCollection: [Object],
       schema: null,
       schemaDelimiter: '',
       defaultScope: {},
       scopes: {},
       indexes: [],
       name: [Object],
       omitNull: false,
       sequelize: [Sequelize],
       hooks: {} },
    _options:
     { isNewRecord: true,
       _schema: null,
       _schemaDelimiter: '',
       include: undefined },
    isNewRecord: false } ]

строк данных в базе данных:

node-sequelize-examples=# select * from "user";
 id | login | password | age | isDeselected
----+-------+----------+-----+--------------
  1 | a     | 123      |     |
  2 | b     | 321      |     |
(2 rows)

node-sequelize-examples=# select * from "group";
 id |  name   | permissions
----+---------+-------------
  1 | group a |
  2 | group b |
  3 | group c |
  4 | group d |
(4 rows)

node-sequelize-examples=# select * from "UserGroup";
 groupId | userId
---------+--------
       1 |      1
       2 |      1
       3 |      2
       4 |      2
       3 |      1
(5 rows)

Версии зависимостей :

"pg": "^7.17.1",
"pg-hstore": "^2.3.3",
"sequelize": "^5.21.3",

исходный код: https://github.com/mrdulin/node-sequelize-examples/tree/master/src/examples/stackoverflow/60686872

...