Reputation: 182
I have two models, Video and Frame.
Frame.belongsTo(models.Video);
Video.hasMany(models.Frame, { as: "Frames" });
I now need a way to specify first and last frame for a video, but can't get it to work.
I tried this:
Video.hasOne(Frame, { as: "FirstFrame" });
Video.hasOne(Frame, { as: "LastFrame" });
but that creates FirstFrameId and LastFrameId in the Frames table instead of the Videos table. I need to have video.get/setFirstFrame() and video.get/setLastFrame() functions available. How can I do this?
Upvotes: 3
Views: 8581
Reputation: 2301
You don't need to set belongTo and hasMany as you show at first. Use only one depending on your db schema.
For get FirstFrameId and LastFrameId on the Videos Model you need to use:
Video.belongsTo(Frame, {as: 'FirstFrame'});
Video.belongsTo(Frame, {as: 'LastFrame'});
This is specify on the Sequelize docs and you can check it here
"Even though it is called a HasOne association, for most 1:1 relations you usually want the BelongsTo association since BelongsTo will add the foreignKey on the source where hasOne will add on the target."
Upvotes: 8