profile
viewpoint

Ask questionsUnable to get many to many working

Been trying to get my Many to Many association to work, but unable to do so. I looked at the example code, but it's not working for me.

// user.model.ts
import { Table, Model, Column, BelongsToMany } from 'sequelize-typescript';
import { Room, UserRoom } from './index';

@Table
class User extends Model<User> {
    @PrimaryKey
    @AutoIncrement
    @Column
    id: number;

    @Column
    spotify_id: number;

    @BelongsToMany(() => Room, () => UserRoom)
    rooms: Room[];
}

export default User;
// room.model.ts
import { Table, Model, Column, BelongsToMany } from 'sequelize-typescript';
import { User, UserRoom } from './index';

@Table
class Room extends Model<Room> {
    @PrimaryKey
    @AutoIncrement
    @Column
    id: number;

    @Column
    name: string;

    @Column
    image: string;

    @BelongsToMany(() => User, () => UserRoom)
    users: User[];
}

export default Room;
// user_room.model.ts
import { Table, Model, Column, ForeignKey, PrimaryKey } from 'sequelize-typescript';
import { Room, User } from './index';

@Table
class UserRoom extends Model<UserRoom> {
    @ForeignKey(() => User)
    @PrimaryKey
    @Column
    user_id: number;

    @ForeignKey(() => Room)
    @PrimaryKey
    @Column
    room_id: number;
}

export default UserRoom;

This results in the following error:

[...]/node_modules/sequelize-typescript/lib/models/association/BaseAssociation.js:55
throw new Error("Foreign key for \"" + relatedClass.name + "\" is missing " +
      ^
Error: Foreign key for "Room" is missing on "User_Room".

Is there something I'm missing? It's basically a 1-1 copy of the example code.

RobinBuschmann/sequelize-typescript

Answer questions kfrajtak

I am experiencing different problem with many-to-many:

@BelongsToMany(() => Role, () => UserRole) roles: Role[];

The error is

(node:41692) UnhandledPromiseRejectionWarning: TypeError: Cannot read property
'prototype' of undefined
    at Sequelize.model (...\node_modules\sequelize-typescript\dist\sequelize\
        sequelize\sequelize.js:25:61)

Via poor man's debugger (i.e. console) I get

BelongsToManyAssociation {
  associatedClassGetter: [Function],
  options:
   { foreignKey: undefined,
     otherKey: undefined,
     through: [Function],
     as: 'roles' } }

and the through function is returning undefined.

Can anybody help?

Thanks, Karel

useful!
source:https://uonfu.com/
Github User Rank List