Я новичок во вселенной NodeJ и использую Sequelize с PostgreSQL для проекта ExpressJs.
У меня возникли некоторые проблемы с поиском правильного способа представления таблицы связи между двумя моделями.
Вот мои две таблицы:
'игроки':
- ID
- 1008 * Firstname *
- 1010 * Фамилия *
- year_of_birth
- навыки
- Войти
- пароль
- created_at
- updated_at
'команды':
- ID
- имя
- created_at
- updated_at
И таблица ассоциации 'team_players':
Приведя несколько примеров в интернете, я попробовал следующий синтаксис:
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";' }