代码之家  ›  专栏  ›  技术社区  ›  shuk

Sequelize有许多include返回对象而不是数组

  •  0
  • shuk  · 技术社区  · 6 年前

    模型定义:

    sequelize.define('Parent', {name: DataTypes.STRING})
    sequelize.define('Child', {name: DataTypes.STRING})
    

    Parent.hasMany(Child, {
      foreignKey: 'parent_id',
      as: 'child'
    })
    
    Child.belongsTo(Parent)
    

    包含功能:

    Parent.findByPk(pk, {
      include: [{
        model: Child,
        as: 'child',
        where: {
          name: 'benny'
        }
      }]
    })
    

    {
      "id": 1,
      "name": "parent name",
      "child": [
        {
          "id": 2
          "name": "benny",
          "parent_id": 1
        }
      ]
    }
    

    我希望它返回的内容(我在文档中没有看到任何支持或提及)

    {
      "id": 1,
      "name": "parent name",
      "child": {
        "id": 2
        "name": "benny",
        "parent_id": 1
      }
    }
    

    区别在于 Child

    1 回复  |  直到 6 年前
        1
  •  2
  •   Aaron Stanley King    6 年前

    http://docs.sequelizejs.com/manual/tutorial/associations.html

    父级.hasOne(儿童{ as:'孩子'

    否则它是一个数组,因为父对象可以有多个数组。

    父级.hasmony(儿童{ as:'儿童'

    如果你真的只关心第一个孩子或单身。。父项.子项[0]

    您可以将自己的函数附加到名为child的父函数上,该父函数只返回子数组中的第一个函数。或者最新的一个。。这个功能由你决定。