簡體   English   中英

Sequelize 多對多添加功能不起作用

[英]Sequelize Many-to-Many add function doesn't work

包.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 不是函數

它應該工作。 這是一個工作示例:

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

暫無
暫無

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

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