我在我的node.js应用程序中使用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',
},
]
}我该怎么做?
我知道我必须在我的用户模型的defaultScope选项中写一些东西,但是什么呢?
实际的Users模型是:
const Users = {
name: 'Users',
model: {
schema: {
id: { type: Sequelize.INTEGER, primaryKey: true, },
name: { type: Sequelize.STRING },
}
options: {
defaultScope: {
// write scope here
}
}
}发布于 2019-03-29 09:13:16
我想出了怎么做(真的很容易做到)
首先更新模型:
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);就这样。
https://stackoverflow.com/questions/55393016
复制相似问题