gpt4 book ai didi

orm - Sequelize 选择与同一实体的两个关系

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

我有 2 个表, ItemLegacy :

module.exports = function(sequelize, DataTypes) {
return sequelize.define('ItemLegacy', {
id: {
type: DataTypes.INTEGER(11).UNSIGNED,
allowNull: false,
primaryKey: true
},
parent: {
type: DataTypes.INTEGER(11),
allowNull: false,
defaultValue: 0,
},
child: {
type: DataTypes.INTEGER(11),
allowNull: false,
defaultValue: 0
}
}, {
tableName: 'ItemLegacy',
timestamps: false,
underscored: false
});
};
和项目:
module.exports = function(sequelize, DataTypes) {
return sequelize.define('Item', {
id: {
type: DataTypes.INTEGER(11).UNSIGNED,
allowNull: false,
primaryKey: true
},
title: {
type: DataTypes.STRING(500),
allowNull: false,
defaultValue: ''
},
code: {
type: DataTypes.STRING(20),
allowNull: true
},
}, {
tableName: 'Item',
timestamps: false,
underscored: false
});
};
我还定义了两个关系:
db.ccnLegacy.hasOne(db.ccn, { foreignKey: 'id', sourceKey: 'parent' })
db.ccnLegacy.hasOne(db.ccn, { foreignKey: 'id', sourceKey: 'child' })
我的问题是,我想使用 select 创建一个 sequelize 请求,并与 parentchild 两个字段中的每一个都有关系。
我知道如何用一个关系做到这一点,但我如何用 2 做到这一点?
我的代码只有一种关系:
db.itemLegacy.findOne({
raw: true,
where: { child: idChild },
include: [
{
model: db.item
},
]
})

最佳答案

您只需为两个关联指定别名并在查询中使用它们。其次,您使用了 hasOne 而不是 belongTo,因为 belongTo 正好用于在 N:1 关系中从 N 到 1 的情况。
协会:

db.ccnLegacy.belongsTo(db.ccn, { foreignKey: 'parent', as: 'Parent' })
db.ccnLegacy.belongsTo(db.ccn, { foreignKey: 'child', as: 'Child' })
询问:
db.itemLegacy.findOne({
raw: true,
where: { child: idChild },
include: [
{
model: db.item,
as: 'Child'
},
{
model: db.item,
as: 'Parent'
},
]
})

关于orm - Sequelize 选择与同一实体的两个关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64156919/

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