表示链接两个模型的关联表

时间:2019-06-04 09:27:43

标签: node.js express sequelize.js

我是NodeJs领域的新手,并且将Sequelize与PostgreSQL一起用于ExpressJs项目。 我在寻找正确的方法来表示两个模型之间的关联表时遇到了一些问题。 这是我的两个桌子:

“玩家”:

  • id
  • 名字
  • 姓氏
  • 出生年月
  • 技能
  • 登录
  • 密码
  • created_at
  • updated_at

“团队”:

  • id
  • 名称
  • created_at
  • updated_at

关联表'team_players':

  • id
  • id_team
  • id_player

给出互联网上的一些示例,我尝试了以下语法:

Player.belongsToMany(Team, {foreignKey: 'id_player', through: 'team_players'});

当我尝试通过这种关联访问数据时:

Player.findAll({ include :[{model: Team,foreignKey: 'id_team', through: 'team_players'}] })
. then(results)[...]

它不起作用。

这是我完成的模型定义。

玩家模型定义:

const { Sequelize } = require('../config/postgres');
const { sequelizeInstance } = require('../config/postgres');

const { Model } = Sequelize;
const Team = require('./Team');

class Player extends Model {}
Player.init({
  firstname: {
    type: Sequelize.STRING,
    allowNull: false,
    validate: {isAlpha: true}
  },
  lastname: {
    type: Sequelize.STRING,
    allowNull: false,
    validate: {isAlpha: true}
  },
  year_of_birth: {
    type: Sequelize.INTEGER,
    allowNull: false,
    validate: {
      min: 1950,
      max: 2019,
      isNumeric: true
    },
  },
  skills: {
    type: Sequelize.INTEGER,
    allowNull: false,
    validate: {isInt: true}
  },
  login: {
    type: Sequelize.STRING,
    allowNull: false,
    validate: 
    {
      isAlphanumeric: true,
      unique: true
    }
  },
  password: {
    type: Sequelize.STRING,
    allowNull: false,
    validate: {isAlphanumeric: true}
  },
},
{
  sequelize: sequelizeInstance,
  timestamps: true,
  modelName: 'player',
  tableName: 'players'
});

Player.belongsToMany(Team, {foreignKey: 'id_player', through: 'team_players'});

module.exports = Player;

团队模型定义:

const { Sequelize } = require('../config/postgres');
const { sequelizeInstance } = require('../config/postgres');

const { Model } = Sequelize;
const Player = require('./Player');

class Team extends Model {}
Team.init({
  name: {
    type: Sequelize.STRING,
    allowNull: false,
    unique: true
  },
},
{
  sequelize: sequelizeInstance,
  timestamps: true,
  modelName: 'team',
  tableName: 'teams'
});

module.exports = Team;

这是错误消息:

  name: 'SequelizeDatabaseError',
  parent:
   { error: column teams->team_players.teamId does not exist
       at Connection.parseE (/home/nku/sources/.perso/pasanga/server/node_modules/pg/lib/connection.js:602:11)
       at Connection.parseMessage (/home/nku/sources/.perso/pasanga/server/node_modules/pg/lib/connection.js:399:19)
       at Socket.<anonymous> (/home/nku/sources/.perso/pasanga/server/node_modules/pg/lib/connection.js:121:22)
       at Socket.emit (events.js:197:13)
       at addChunk (_stream_readable.js:288:12)
       at readableAddChunk (_stream_readable.js:269:11)
       at Socket.Readable.push (_stream_readable.js:224:10)
       at TCP.onStreamRead [as onread] (internal/stream_base_commons.js:150:17)
     name: 'error',
     length: 125,
     severity: 'ERROR',
     code: '42703',
     detail: undefined,
     hint: undefined,
     position: '776',
     internalPosition: undefined,
     internalQuery: undefined,
     where: undefined,
     schema: undefined,
     table: undefined,
     column: undefined,
     dataType: undefined,
     constraint: undefined,
     file: 'parse_relation.c',
     line: '3293',
     routine: 'errorMissingColumn',
     sql:
      'SELECT "player"."id", "player"."firstname", "player"."lastname", "player"."yob", "player"."skills", "player"."login", "player"."password", "player"."created_at", "player"."updated_at", "teams"."id" AS "teams.id", "teams"."name" AS "teams.name", "teams"."created_at" AS "teams.created_at", "teams"."updated_at" AS "teams.updated_at", "teams->team_players"."created_at" AS "teams.team_players.created_at", "teams->team_players"."updated_at" AS "teams.team_players.updated_at", "teams->team_players"."id_player" AS "teams.team_players.id_player", "teams->team_players"."teamId" AS "teams.team_players.teamId" FROM "players" AS "player" LEFT OUTER JOIN ( "team_players" AS "teams->team_players" INNER JOIN "teams" AS "teams" ON "teams"."id" = "teams->team_players"."teamId") ON "player"."id" = "teams->team_players"."id_player";' }

1 个答案:

答案 0 :(得分:0)

您与玩家对团队的关联还可以。我认为您可以通过将team_players.id_team重命名为默认名称team_players.teamId

来解决问题

或者,您可以从“团队到玩家”中添加一个关联,以便处理您选择的外键,如下所示:

Team.belongsToMany (Player,{foreignKey: 'id_team', through: 'team_players'});

6月5日编辑

以下是一些工作代码:

const Sequelize = require('sequelize');
const node_app_name = require("../sqltest");  // my db instance here
const { Model } = Sequelize;

class Player extends Model {}
Player.init({
  firstname: Sequelize.STRING,
  lastname: Sequelize.STRING,
},
{sequelize: node_app_name.sequelizeDB});

class Team extends Model {}
Team.init({
  name: Sequelize.STRING
},
{sequelize: node_app_name.sequelizeDB});

class TeamPlayer extends Model {}
TeamPlayer.init({
    id_team: Sequelize.INTEGER,
    id_player: Sequelize.INTEGER,
},
{sequelize: node_app_name.sequelizeDB}); 

Player.belongsToMany(Team, {foreignKey: 'id_player', through: TeamPlayer});
Team.belongsToMany (Player,{foreignKey: 'id_team', through: TeamPlayer});

Player.findAll({    
    include: 
       [{
          model: Team,
          required: false
        }]
}).then(pat => {
   console.log(pat);
});

希望这会有所帮助。请注意,belongsToMany()关联发生在之后两个模型都已初始化。