Cat*_*ish 3 javascript node.js sequelize.js
我创建了此记录,您可以看到它具有2个标签-tag1和tag2
{
"id": "d87de1d9-b048-4867-92fb-a84dca59c87e",
"name": "Test Name",
"tags": [
{
"id": "fa0ca8fd-eff4-4e58-8bb0-a1ef726f01d4",
"name": "tag1",
"organizationId": "d87de1d9-b048-4867-92fb-a84dca59c87e",
"updatedAt": "2018-12-05T18:53:56.867Z",
"createdAt": "2018-12-05T18:53:56.867Z"
},
{
"id": "66e758af-9907-4278-8c4f-f8fb2bf9aea9",
"name": "tag2",
"organizationId": "d87de1d9-b048-4867-92fb-a84dca59c87e",
"updatedAt": "2018-12-05T18:53:56.867Z",
"createdAt": "2018-12-05T18:53:56.867Z"
}
],
"updatedAt": "2018-12-05T18:53:56.860Z",
"createdAt": "2018-12-05T18:53:56.860Z"
}
Run Code Online (Sandbox Code Playgroud)
我想编写一个查询,查找包含tag1并返回包括所有标签在内的整个组织的组织。
我目前有这个查询,它只返回与查询匹配的标签记录,而不是所有标签。
db.organization.findAll({
include: {
model: db.tag,
where: { name: 'tag1' }
}
})
Run Code Online (Sandbox Code Playgroud)
并产生这个结果
[
{
"id": "3d03d74e-82ec-485e-aa29-abe9e8b0f0e9",
"name": "Test Name",
"createdAt": "2018-12-05T19:29:40.685Z",
"updatedAt": "2018-12-05T19:29:40.685Z",
"tags": [
{
"id": "75dc9cd2-5e20-4aa6-b86e-cbaa2c896d57",
"name": "tag1", <-- NOTE THAT ONLY TAG1 IS IN THE RESULTS EVEN THOUGH THERE SHOULD BE ANOTHER TAG OBJECT RETURNED
"createdAt": "2018-12-05T19:29:40.694Z",
"updatedAt": "2018-12-05T19:29:40.694Z",
"organizationId": "3d03d74e-82ec-485e-aa29-abe9e8b0f0e9"
}
]
}
]
Run Code Online (Sandbox Code Playgroud)
如何编写查询来做到这一点?
我在这个问题上进行了很多搜索,我认为最有效的方法(在这种情况下)是建立基本的过滤关联并接收数据
关联文件
// This is for filtering
organization.hasMany(tag, {
foreignKey: 'organizationId',
});
// This one is for receiving data after filtering
organization.hasMany(tag, {
foreignKey: 'organizationId',
as: 'tags',
});
Run Code Online (Sandbox Code Playgroud)
控制者
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);
Run Code Online (Sandbox Code Playgroud)
在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": "...",
}
]
}
]
Run Code Online (Sandbox Code Playgroud)
来自GitHub的一些资源:不能从sequelize#3664中的select语句中排除关联的字段
| 归档时间: |
|
| 查看次数: |
264 次 |
| 最近记录: |