我创建了 oneToMany 关系,但我如何获得单条记录属于 Sequalize 中的多条记录
I created oneToMany relation but how I can get the single record belongs to the many record in Sequalize
标签类别模型
export const TagCategories = sequelize.define(
"tag_categories",
{
categoryId: {
type: DataTypes.INTEGER,
field: "category_id",
autoIncrement: true,
primaryKey: true,
},
title: {
type: DataTypes.STRING(50),
field: "title",
allowNull: false,
unique: true,
},
},
);
TagCategories.hasMany(TagGroups, {
foreignKey: "categoryId",
sourceKey: "categoryId",
});
export default TagCategories;
标签组模型
export const TagGroups = sequelize.define(
"tag_groups",
{
tagGroupId: {
type: DataTypes.INTEGER,
field: "tag_group_id",
autoIncrement: true,
primaryKey: true,
},
categoryId: {
type: DataTypes.INTEGER,
field: "category_id",
allowNull: false,
},
title: {
type: DataTypes.STRING(50),
field: "title",
allowNull: false,
unique: true,
},
},
);
在上述模型中,我在 TagCategories 和 TagGroups 之间建立了 oneToMany 关系
但我想从 TagGroup table 中获取包含 TagCategories 详细信息的记录。
提前致谢
你看过 official documentation 中的示例了吗?
此外,您需要添加从 TagGroups
到 TagCategories
:
的关联
// there is no need to indicate `sourceKey` if this field is a primary key
TagGroups.belongsTo(TagCategories, {
foreignKey: "categoryId",
});
最好在静态函数中定义所有关联,并在所有模型注册后单独调用它们。
查看问题和我的回答怎么做
在你的情况下,最终请求将是这样的
const tagGroup = await TagGroups.findOne({
where: {
tagGroupId: groupId
},
include: [{
model: TagCategories
}]
})
标签类别模型
export const TagCategories = sequelize.define(
"tag_categories",
{
categoryId: {
type: DataTypes.INTEGER,
field: "category_id",
autoIncrement: true,
primaryKey: true,
},
title: {
type: DataTypes.STRING(50),
field: "title",
allowNull: false,
unique: true,
},
},
);
TagCategories.hasMany(TagGroups, {
foreignKey: "categoryId",
sourceKey: "categoryId",
});
export default TagCategories;
标签组模型
export const TagGroups = sequelize.define(
"tag_groups",
{
tagGroupId: {
type: DataTypes.INTEGER,
field: "tag_group_id",
autoIncrement: true,
primaryKey: true,
},
categoryId: {
type: DataTypes.INTEGER,
field: "category_id",
allowNull: false,
},
title: {
type: DataTypes.STRING(50),
field: "title",
allowNull: false,
unique: true,
},
},
);
在上述模型中,我在 TagCategories 和 TagGroups 之间建立了 oneToMany 关系
但我想从 TagGroup table 中获取包含 TagCategories 详细信息的记录。
提前致谢
你看过 official documentation 中的示例了吗?
此外,您需要添加从 TagGroups
到 TagCategories
:
// there is no need to indicate `sourceKey` if this field is a primary key
TagGroups.belongsTo(TagCategories, {
foreignKey: "categoryId",
});
最好在静态函数中定义所有关联,并在所有模型注册后单独调用它们。
查看问题和我的回答
在你的情况下,最终请求将是这样的
const tagGroup = await TagGroups.findOne({
where: {
tagGroupId: groupId
},
include: [{
model: TagCategories
}]
})