续集一对一的关系 [英] Sequelize one to one relation

查看:27
本文介绍了续集一对一的关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个模型,视频和帧.

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?

推荐答案

你不需要像一开始展示的那样设置belongTo和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 会添加hasOne 将添加到目标的源上的 foreignKey."

"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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆