Sandro Simas
Sandro Simas

Reputation: 1307

Confused about sequelize associations One-To-Many and One-To-One unidirectional

I have the follow entities:

User hasMany Goal - It works fine. A foreign key is added to goal table
User hasOne Photo - Doesn't work.
Goal hasMany Photo on join table model GoalPhoto - Doesn't work.

The Photo hasn't any association with User and Goal, but the User and the Goal entities has a One-To-One and One-To-Many respectively. Photo doesn't belongs to any model.

When i put User.hasOne(Photo) it creates the foreign key in Photo table, but i want just a foreignKey in User (fk_photo). When i put Goal.hasMany(Photo, { as: 'photos', joinTableModel: GoalPhoto, foreignKey: 'fk_goal' }) it creates the foreign key in Photo table, but i want a JoinTable with Goal and Photo foreign keys.

How can i solve that ?

Upvotes: 1

Views: 2860

Answers (1)

Sergey Karasev
Sergey Karasev

Reputation: 4843

Create foreign key (photo_id) in User table:

User = sequelize.define('User', {});
Photo = sequelize.define('Photo', {});
Photo.hasOne(User);
User.belongsTo(Photo);

Create JoinTable:

GoalPhoto = sequelize.define('GoalPhoto', {});
Goal.hasMany(Photo, {through: GoalPhoto});
Photo.hasMany(Goal, {through: GoalPhoto});

Upvotes: 1

Related Questions