shuk
shuk

Reputation: 1823

Sequelize hasMany include to return object rather than array

Model Definitions:

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

Associations:

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

Child.belongsTo(Parent)

Include function:

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

What it returns (usual behavior):

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

What I wish it to return (I do not see any support or mention in docs)

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

Difference is Child is configured to return as object

Has anyone met this challenge?

Upvotes: 1

Views: 4445

Answers (1)

Aaron Stanley King
Aaron Stanley King

Reputation: 79

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

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

else it is an array because the parent can have more than one.

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

If you really only care about the first child or single.. Parent.children[0]

You can tack on your own function to the Parent called child that returns just that first one in the children array. Or latest one by date.. its up to you on that function.

Upvotes: 2

Related Questions