我搜索了很多关于这个主题的内容,我认为最有效的方法(在这种情况下)是建立一个基本的过滤关联和一个接收数据的关联
协会文件
// This is for filtering
organization.hasMany(tag, {
foreignKey: 'organizationId',
});
// This one is for receiving data after filtering
organization.hasMany(tag, {
foreignKey: 'organizationId',
as: 'tags',
});
控制器
const results = await db.organization.findAll({
include: [{
model: db.tag,
where: { name: 'tag1' },
attributes: [], // remove 'Tag' property from results
}, {
model: db.tag,
as: 'tags',
}],
});
console.log(results);
The console.log(results);
将返回:
[
{
"id": "...",
"name": "Organization Test Name",
"createdAt": "...",
"updatedAt": "...",
// "Tag": [ // This property was removed by 'attributes: []'
// {
// "id": "...",
// "name": "tag1",
// "organizationId": "..."
// "createdAt": "...",
// "updatedAt": "...",
// },
// ],
"tags": [
{
"id": "...",
"name": "tag1",
"organizationId": "..."
"createdAt": "...",
"updatedAt": "...",
},
{
"id": "...",
"name": "tag1",
"organizationId": "..."
"createdAt": "...",
"updatedAt": "...",
}
]
}
]
来自 GitHub 的一些资源:无法从sequelize中的select语句中排除关联的字段#3664 https://github.com/sequelize/sequelize/issues/8754