Per Arne Andersen
Per Arne Andersen

Reputation: 544

Sequelize 1:n association

I have following tables:

--Cable--
|id|name|

--Cable_Part--
|id|fk_cable|data|

Example of data is:

Cable:
1 - Cable One

Cable_Part:
1 - 1 - Some data
2 - 1 - More data
3 - 1 - Even more data

I wish to retrieve each of these cable parts as a array/object in my query. Ive tried following relation:

@Model.Cable.belongsToMany @Model.CablePart,
{
    through: 'cable_part'
    foreignKey: 'cable'
}

Im getting this error:

Possibly unhandled Error: CablePart (CablePart) is not associated to Cable!

Also, it seems that hasMany is deprecated as I'm getting this message if I'm attempting to use it

Using 2 x hasMany to represent N:M relations has been deprecated. Please use belongsToMany instead

I'm sure this association should be easy to make, but it seems like it doesnt work whatever I attempt to do.

The Query i'm attempting to do:

  that.Database.Model.Cable.all(
    include:
      [
        {
          model: that.Database.Model.CablePart
          as: 'CablePart'
        }
      ]

  ).then (cables)->

EDIT: This is a 1:n not a n:m, using following mapping still gives an error:

@Model.CablePart.belongsTo @Model.Cable,
{
    foreignKey: 'cable'
}
@Model.Cable.hasMany @Model.CablePart,
{
    foreignKey: 'cable'
}

Error is:

Possibly unhandled Error: Include unexpected. Element has to be either a Model, an Association or an object.

Upvotes: 0

Views: 1080

Answers (1)

Jan Aagaard Meier
Jan Aagaard Meier

Reputation: 28788

through and belongsToMany are for n:m associations. through specifies the join table, so it is not needed in your case.

The Include unexpected error suggests that that.Database.Model.CablePart might be undefined. Also, remove the as part of the include - that is only needed if you specify as on the association

Upvotes: 1

Related Questions