一对一关系 [英] Sequelize one to one relation
问题描述
我有两个模型,视频和帧.
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.
我尝试过:
Video.hasOne(Frame, { as: "FirstFrame" });
Video.hasOne(Frame, { as: "LastFrame" });
但是在Frames表而不是Videos表中创建FirstFrameId和LastFrameId.我需要有可用的video.get/setFirstFrame()和video.get/setLastFrame()函数.我该怎么办?
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?
推荐答案
您不需要像最初显示的那样设置belongeTo和hasMany.只能使用一种,具体取决于您的数据库架构.
You don't need to set belongTo and hasMany as you show at first. Use only one depending on your db schema.
要在视频模型上获取FirstFrameId和LastFrameId,您需要使用:
For get FirstFrameId and LastFrameId on the Videos Model you need to use:
Video.belongsTo(Frame, {as: 'FirstFrame'});
Video.belongsTo(Frame, {as: 'LastFrame'});
这是在Sequelize文档上指定的,您可以在此处进行检查>
This is specify on the Sequelize docs and you can check it here
即使它被称为HasOne关联,对于大多数1:1关系 您通常需要BelongsTo关联,因为BelongsTo将添加 源上的foreignKey,hasOne将添加到目标上."
"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."
这篇关于一对一关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!