javascript - 在另一个模型上使用 getModel 时获取关联 sequelize

标签 javascript sequelize.js

我想在通过我的用户实例获取团队时包含团队关联。我找不到办法做到这一点。

const userTeams = await user.getTeams({
      joinTableAttributes: []
});

我尝试通过传递“包含”来做到这一点,例如:
const userTeams = await user.getTeams({
    joinTableAttributes: [],
    include: { model: Board, as: 'boards', through: { attributes: [] } }
});

最佳答案

user 模型上调用 team 方法之前,您需要定义 getTeamsUser 的关联。

例如。
index.ts :

import { sequelize } from '../../db';
import { Model, DataTypes, HasManyGetAssociationsMixin } from 'sequelize';

class User extends Model {
  public getTeams!: HasManyGetAssociationsMixin<Team>;
}
User.init({}, { sequelize, modelName: 'user' });

class Team extends Model {}
Team.init(
  {
    name: DataTypes.STRING,
  },
  { sequelize, modelName: 'team' },
);

User.hasMany(Team);

(async function test() {
  try {
    await sequelize.sync({ force: true });
    const user = await User.create({ teams: [{ name: 'Bull' }, { name: 'Thunder' }] }, { include: [Team] });
    const teams = await user.getTeams();
    const teamDataValues = teams.map((team) => team.dataValues);
    console.log('teamDataValues: ', teamDataValues);
  } catch (error) {
    console.log(error);
  } finally {
    await sequelize.close();
  }
})();

执行结果:

{ POSTGRES_HOST: '127.0.0.1',
  POSTGRES_PORT: '5430',
  POSTGRES_PASSWORD: 'testpass',
  POSTGRES_USER: 'testuser',
  POSTGRES_DB: 'node-sequelize-examples' }
Executing (default): DROP TABLE IF EXISTS "team" 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 , 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 "team" CASCADE;
Executing (default): CREATE TABLE IF NOT EXISTS "team" ("id"   SERIAL , "name" VARCHAR(255), "userId" INTEGER REFERENCES "user" ("id") ON DELETE SET NULL ON UPDATE CASCADE, 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 = 'team' GROUP BY i.relname, ix.indexrelid, ix.indisprimary, ix.indisunique, ix.indkey ORDER BY i.relname;
Executing (default): INSERT INTO "user" ("id") VALUES (DEFAULT) RETURNING *;
Executing (default): INSERT INTO "team" ("id","name","userId") VALUES (DEFAULT,$1,$2) RETURNING *;
Executing (default): INSERT INTO "team" ("id","name","userId") VALUES (DEFAULT,$1,$2) RETURNING *;
Executing (default): SELECT "id", "name", "userId" FROM "team" AS "team" WHERE "team"."userId" = 1;
teamDataValues:  [ { id: 1, name: 'Bull', userId: 1 },
  { id: 2, name: 'Thunder', userId: 1 } ]

查看数据库中的数据记录:

node-sequelize-examples=# select * from "user";
 id
----
  1
(1 row)

node-sequelize-examples=# select * from "team";
 id |  name   | userId
----+---------+--------
  1 | Bull    |      1
  2 | Thunder |      1
(2 rows)

关于javascript - 在另一个模型上使用 getModel 时获取关联 sequelize,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60252867/

相关文章:

mysql - 无法使用sequelize运行连接查询

javascript - 将多个对象从 Angular 保存到 Sequelize

javascript - 如何检测地址栏中的 ENTER 按键/或 "GO"按钮?

javascript - 地理坐标附近的 Google 用户图像

javascript - JQuery ajax 使用复选框对象回发 id

node.js - Sequelize 关联 hasOne,belongsTo

sql-server - Sequelize-cli 不执行任何操作

sequelize.js - 保存前Sequelize计算值

javascript - openlayers、decarta 和 google maps 之间的性能差异

javascript - 为什么javascript会覆盖Html代码