gpt4 book ai didi

sequelize.js - Sequelize - 两个表之间的一对多关系

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

我是 Sequelize 的新手。我正在尝试配置两个表之间的一对多关系。
我有两个表,区域和 prime_siblings,我需要的是区域可以有很多 prime_siblings 。当我运行下一个代码时,我没有收到错误消息,但是我的列 prime_siblings 没有同步。
这是我的模型及其关联:zones

    module.exports = function (sequelize, DataTypes) {
const zones = sequelize.define('zones', {
id: {
primaryKey: true,
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
},
name: DataTypes.STRING(50),
}, {
tableName: 'zones',
underscored: true,
});

zones.associate = (models) => {
zones.hasMany(models.prime_siblings, {
as: 'prime_siblings',
foreignKey: 'zones_id',
});
};

return zones;
};
prime_siblings

module.exports = function (sequelize, DataTypes) {
const primeSiblings = sequelize.define('prime_siblings', {
id: {
primaryKey: true,
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
timestamps: false,
},
zones_id: {
primaryKey: true,
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
timestamps: false,
},
}, {
tableName: 'prime_siblings',
underscored: true,
});

primeSiblings.associate = (models) => {
primeSiblings.belongsTo(models.zones, {
foreignKey: 'zones_id',
});
};
return primeSiblings;
};
表已成功创建,然后使用 postman ,我使用发布区域的端点。
这是终点
    router.post('/', (req, res, _next) => {
models.zones.findByPk('0333008d-fae4-4419-a22d-bf14aef782bb', { include: ['prime_siblings'] });
models.zones.findAll({ include: ['prime_siblings'] });
return helpers.save(models.zones, req, res);
}
return res.status(401).send({
code: 'UNAUTHORIZED', message: 'Unauthorized action',
});

这是我的 body :

{
"id":"0333008d-fae4-4419-a22d-bf14aef782bb",
"name":"BS AS NOROESTE CENTRO",
"created_at":"2020-03-24T17:27:52.000Z",
"updated_at":"2021-05-13T18:59:09.000Z",
"prime_siblings": ["sibling_zone_id_1", "sibling_zone_id_2", "sibling_zone_id_3"]
}

从理论上讲,这应该添加 3 行包含这些数据:
    zone_id_0 sibling_zone_id_1
zone_id_0 sibling_zone_id_2
zone_id_0 sibling_zone_id_3
我已经搜索并尝试了多种方法,但没有成功。

最佳答案

/* Requiring the models created with sequelize */
const { zones, prime_siblings } = require("./models");

async function createZone(zone) {
try {
/* The create method receive the data and options. Include is an option for including more than a model */
await zones.create(zone, {
include: [
{
model: prime_siblings,
as: "prime_siblings", // This alias should match with the alias defined in the association
},
],
});
} catch (error) {
console.error(error);
}
}

createZone({
id: "0333008d-fae4-4419-a22d-bf14aef782bb",
name: "BS AS NOROESTE CENTRO",
created_at: "2020-03-24T17:27:52.000Z",
updated_at: "2021-05-13T18:59:09.000Z",
prime_siblings: [{}, {}, {}], // This array contains the objects to be created (associated with the main model)
});

关于sequelize.js - Sequelize - 两个表之间的一对多关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67591410/

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