javascript - 在 sequelize 范围内包含一对多关联
问题描述
我sequelize
在我的 node.js 应用程序中使用。
我有两个表:用户和图像。
用户表与图像是一对多的关系。因此,每个用户都可以拥有一个或多个图像。
Users Images
+------+----------+ +------+-----------------------+--------+
| id | name | | id | url | UserId |
+------+----------+ +------+-----------------------+--------+
| 123 | Markus | | 542 | https://et.ly/e2ts | 123 |
| 456 | Thomas | | 731 | https://et.ly/dwas | 123 |
+------+----------+ | 626 | https://et.ly/2w6i | 456 |
+------+-----------------------+--------+
我想要一个范围,当我查询一个或多个用户时,我会得到这样的结果:
// Users.findById(123)
{
id: 123,
name: 'Markus',
images: [
{
id: 542,
url: 'https://et.ly/e2ts',
},
{
id: 731,
url: 'https://et.ly/dwas',
},
]
}
我怎样才能做到这一点?
我知道我必须在我的 User 模型的 defaultScope 选项中写一些东西,但是什么?
实际Users
模型是:
const Users = {
name: 'Users',
model: {
schema: {
id: { type: Sequelize.INTEGER, primaryKey: true, },
name: { type: Sequelize.STRING },
}
options: {
defaultScope: {
// write scope here
}
}
}
解决方案
我已经知道该怎么做(真的很容易成为现实)
首先更新模型:
const Users = {
name: 'Users',
model: {
schema: {
id: { type: Sequelize.INTEGER, primaryKey: true, },
name: { type: Sequelize.STRING },
}
options: {
defaultScope: {
include: [{
model: Images, as: 'images' // LIKE THIS
}]
}
}
}
然后在定义所有模型时定义关联:
Users.hasMany(Images, { as: 'images' });
Images.belongsTo(Users);
而已。
推荐阅读
- javascript - NodeJS - 一分钟后电子托盘图标消失
- r - 比较多列中的字符(因子)
- css - 减少 SASS 函数生成的 CSS 数量
- dialogflow-es - dialogFlow 中是否有办法将所有意图更改为 endInteraction 为真?
- android - 如何保存地图
从 Flutter 到 Firestore - r - 如何对具有不同长度的多个站点数据执行 Mann Kendall 测试并在 R 中的单个数据帧中输出?
- python - 如何在输入框中打印新行?
- ios - 在 iOS 13 上,AVPlayer 会为此 HLS 视频选择仅音频流。我可以控制这种行为,而是让它加载视频+音频吗?
- python - Jedi - Python 自动完成(提示)不显示方法或建议
- android - 如何以编程方式确定应用程序是否作为来自 Play Market 的捆绑包构建运行