gpt4 book ai didi

node.js - Sequelize - 仅返回关系

转载 作者:行者123 更新时间:2023-12-03 22:19:05 30 4
gpt4 key购买 nike

我有一个问题,我需要从我的 flows 关系中返回一个数组。如何获得一个包含所有公司流量列表的数组?
我的模型和迁移是正确的,我只是不知道如何让查询只返回 flows
公司模式

module.exports = (sequelize) => {
const company = sequelize.define('company', {
id: {
allowNull: false,
autoIncrement: true,
primaryKey: true,
type: DataTypes.INTEGER
},
uuid: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4
},
name: {
type: DataTypes.STRING,
allowNull: false
}
})

company.hasMany(sequelize.models.flow, {foreignKey: 'company_id', as: 'flows'})
}
流动模型
module.exports = (sequelize) => {
const flow = sequelize.define('flow', {
id: {
allowNull: false,
autoIncrement: true,
primaryKey: true,
type: DataTypes.INTEGER
},
company_id: {
allowNull: false,
type: DataTypes.INTEGER
},
uuid: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4
},
name: {
type: DataTypes.STRING,
allowNull: false
},
description: {
type: DataTypes.TEXT
}
})

flow.belongsTo(sequelize.models.company, {foreignKey: 'company_id', as: 'company'})
}
询问
const companies = await ORM.models.company
.findAll({
include: [{
model: ORM.models.flow,
as: 'flows'
}]
})
此查询返回如下:
[
{
"id": 1,
"uuid": "f0c1a5e1-c54c-4083-8284-5a9b272e8ba1",
"name": "Company 1",
"created_at": "2021-02-11T05:47:55.830Z",
"updated_at": "2021-02-11T05:47:55.830Z",
"flows": [
{
"id": 1,
"company_id": 1,
"uuid": "768262d2-88b7-4e0f-81e8-30d7253aae65",
"name": "Flow 1",
"description": null,
"created_at": "2021-02-11T05:48:10.211Z",
"updated_at": "2021-02-11T05:48:10.211Z",
"companyId": 1
}
]
},
{
"id": 2,
"uuid": "3dea2541-a505-4f0c-a356-f1a2d449d050",
"name": "Company 1",
"created_at": "2021-02-11T05:48:11.872Z",
"updated_at": "2021-02-11T05:48:11.872Z",
"flows": [
{
"id": 2,
"company_id": 2,
"uuid": "3e66e8e6-3754-41e5-93ca-6e8ed49e2025",
"name": "Flow 2",
"description": null,
"created_at": "2021-02-11T05:48:20.743Z",
"updated_at": "2021-02-11T05:48:20.743Z",
"companyId": 2
}
]
}
]
我需要像这样返回:
[
{
"id":1,
"company_id":1,
"uuid":"768262d2-88b7-4e0f-81e8-30d7253aae65",
"name":"Flow 1",
"description":null,
"created_at":"2021-02-11T05:48:10.211Z",
"updated_at":"2021-02-11T05:48:10.211Z",
"companyId":1
},
{
"id":2,
"company_id":2,
"uuid":"3e66e8e6-3754-41e5-93ca-6e8ed49e2025",
"name":"Flow 2",
"description":null,
"created_at":"2021-02-11T05:48:20.743Z",
"updated_at":"2021-02-11T05:48:20.743Z",
"companyId":2
}
]

最佳答案

如果你只是想要相关数据,为什么要在中取公司相关数据呢?也许,您只能获取 数据。

const flows = await ORM.models.flow
.findAll({
where: ....,
..........
});
如果无论如何,您仍然想显示特定公司的流程而不显示公司模型的任何属性,只需执行以下操作:
const companies = await ORM.models.company
.findAll({
attributes: [], //empty
include: [{
model: ORM.models.flow,
as: 'flows'
}]
});

关于node.js - Sequelize - 仅返回关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66149385/

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