Reputation: 1694
I am using sequelize for my postgres database and I have the following two tables:
They are previously defined using sequelize.define
It is an M:N relationship, so I decided to go with the following associations:
Artist.belongsToMany(Albums, { through: 'ArtistAlbums' }
Album.belongsToMany(Artist, { through: 'ArtistAlbums' }
This works well, however the table ArtistAlbums later on has very weird column names:
"ArtistArtistId", "AlbumAlbumId" referring to the primary keys of Artist (artistId) and Album (albumId). However I'd like to only have "albumId" and "artistId" in there, but can't figure out how to tell sequelize to do just that. I tried the following:
Issue: I'd have my keys as well as the generated keys in the table
unique: false
option to it, which also did not work.Any help appreciated!
EDIT 1:
I think using otherKey I was able to set one of the columns to the name I want it to be, but not the other.
Upvotes: 1
Views: 1532
Reputation: 2276
Try this:
Artist.belongsToMany(Album, {
through: 'ArtistAlbums',
unique: false,
foreignKey: 'artistId'
});
Album.belongsToMany(Artist, {
through: 'ArtistAlbums',
unique: false,
foreignKey: 'albumId'
});
Note that the only difference between my code and yours is the foreignKey
definition.
The code above created the following result in my postgreSQL DB. (I omitted some data):
CREATE TABLE public."ArtistAlbums"
(
"createdAt" timestamp with time zone NOT NULL,
"updatedAt" timestamp with time zone NOT NULL,
"artistId" integer NOT NULL,
"albumId" integer NOT NULL,
CONSTRAINT "ArtistAlbums_pkey" PRIMARY KEY ("artistId", "albumId"),
CONSTRAINT "ArtistAlbums_albumId_fkey" FOREIGN KEY ("albumId")
REFERENCES public."Album" (id) MATCH SIMPLE
ON UPDATE CASCADE ON DELETE CASCADE,
CONSTRAINT "ArtistAlbums_artistId_fkey" FOREIGN KEY ("artistId")
REFERENCES public."Artist" (id) MATCH SIMPLE
ON UPDATE CASCADE ON DELETE CASCADE
)
To produce the other tables I used:
const Artist = sequelize.define(
'Artist',
{
id: {
type: DataTypes.INTEGER,
primaryKey: true
}
},
{
freezeTableName: true
}
);
const Album = sequelize.define(
'Album',
{
id: {
type: DataTypes.INTEGER,
primaryKey: true
}
},
{
freezeTableName: true
}
);
Upvotes: 1