序列化sequelize嵌套模型

时间:2018-04-22 11:22:31

标签: sequelize.js feathersjs

在设置完所有内容之后我使用了羽毛+ 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 hook中我有下一个代码

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.name : 'Name'
}

我希望有一个对象

{
  description: {name: 'Name' }
}

它应该是一行修复,但不幸的是我无法弄清楚

1 个答案:

答案 0 :(得分:0)

无论遇到同样的问题,解决方案都非常简单,您只需要添加一个布尔标志

  

raw: false,

在你的羽毛服务中