gpt4 book ai didi

javascript - 查询至少有 1 个关联的地方,但返回所有

转载 作者:搜寻专家 更新时间:2023-11-01 00:11:22 24 4
gpt4 key购买 nike

我创建了这条记录,您可以看到它有 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"
}

我想编写一个查询来查找包含 tag1 的组织并返回包括所有标签的整个组织。

我目前有这个查询,它只返回匹配查询的标签记录,而不是所有标签。

db.organization.findAll({
include: {
model: db.tag,
where: { name: 'tag1' }
}
})

它产生了这个结果

[
{
"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"
}
]
}
]

如何编写查询来执行此操作?

最佳答案

我搜索了很多关于这个主题的内容,我认为最有效的方法(在这种情况下)是建立一个基本的过滤关联和一个接收数据的关联

关联文件

// This is for filtering
organization.hasMany(tag, {
foreignKey: 'organizationId',
});

// This one is for receiving data after filtering
organization.hasMany(tag, {
foreignKey: 'organizationId',
as: 'tags',
});

Controller

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);

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 的一些资源:Can't exclude association's fields from select statement in sequelize #3664

关于javascript - 查询至少有 1 个关联的地方,但返回所有,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53639482/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com