序列化 sequelize 嵌套模型
Serializing sequelize nested model
我在设置所有内容后使用 feathers + sequlize + postgres 我有 2 个模型类别和类别描述并尝试在它们之间建立关系,它看起来像这样:
类别模型
const categories = sequelizeClient.define('categories', {
id: {
type: DataTypes.INTEGER,
autoIncrement: true,
primaryKey: true,
}
}, {
hooks: {
beforeCount(options) {
Object.assign(options, { raw: true });
},
},
})
categories.associate = (models) => {
categories.hasOne(models.category_description, {
as: 'description',
foreignKey: 'category_id',
});
};
品类描述模型
const categoryDescription = sequelizeClient.define('category_description', {
id: {
type: DataTypes.INTEGER,
autoIncrement: true,
primaryKey: true,
},
category_id: {
type: DataTypes.INTEGER,
allowNull: false,
},
language_id: {
type: DataTypes.INTEGER,
allowNull: false,
},
name: {
type: DataTypes.STRING,
allowNull: true,
},
}, {
hooks: {
beforeCount(options) {
Object.assign(options, { raw: true });
},
},
});
categoryDescription.associate = (models) => {
categoryDescription.belongsTo(models.categories, {
foreignKey: 'category_id',
});
在 find/get 钩子中我有下一个代码
function (context) {
context.params.sequelize = {
include: [{
model: context.app.service('category-description').Model,
as: 'description',
attributes: ['name'],
where: { language_id: 2 },
}],
};
return Promise.resolve(context);
},
除了一个小问题外,它工作得很好,当我试图查询类别时 "description" 字段填充在 "dot notation"
{
description.name : 'Name'
}
我的期望是有一个对象
{
description: {name: 'Name' }
}
应该是一行修复,可惜我搞不懂
谁遇到了同样的问题,解决方法很简单,你只需要添加一个布尔标志
raw: false,
为您效劳
我在设置所有内容后使用 feathers + sequlize + postgres 我有 2 个模型类别和类别描述并尝试在它们之间建立关系,它看起来像这样:
类别模型
const categories = sequelizeClient.define('categories', {
id: {
type: DataTypes.INTEGER,
autoIncrement: true,
primaryKey: true,
}
}, {
hooks: {
beforeCount(options) {
Object.assign(options, { raw: true });
},
},
})
categories.associate = (models) => {
categories.hasOne(models.category_description, {
as: 'description',
foreignKey: 'category_id',
});
};
品类描述模型
const categoryDescription = sequelizeClient.define('category_description', {
id: {
type: DataTypes.INTEGER,
autoIncrement: true,
primaryKey: true,
},
category_id: {
type: DataTypes.INTEGER,
allowNull: false,
},
language_id: {
type: DataTypes.INTEGER,
allowNull: false,
},
name: {
type: DataTypes.STRING,
allowNull: true,
},
}, {
hooks: {
beforeCount(options) {
Object.assign(options, { raw: true });
},
},
});
categoryDescription.associate = (models) => {
categoryDescription.belongsTo(models.categories, {
foreignKey: 'category_id',
});
在 find/get 钩子中我有下一个代码
function (context) {
context.params.sequelize = {
include: [{
model: context.app.service('category-description').Model,
as: 'description',
attributes: ['name'],
where: { language_id: 2 },
}],
};
return Promise.resolve(context);
},
除了一个小问题外,它工作得很好,当我试图查询类别时 "description" 字段填充在 "dot notation"
{
description.name : 'Name'
}
我的期望是有一个对象
{
description: {name: 'Name' }
}
应该是一行修复,可惜我搞不懂
谁遇到了同样的问题,解决方法很简单,你只需要添加一个布尔标志
raw: false,
为您效劳