標簽類別模型
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 關系
但我想使用 TagCategories 詳細資訊從 TagGroup 表中獲取記錄。
提前致謝
uj5u.com熱心網友回復:
你看過官方檔案中的例子嗎?此外,您需要從to
添加關聯:TagGroupsTagCategories
// 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
}]
})
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/426920.html
