build instance with n:m associated object

10 views
Skip to first unread message

Ариэль Антонов

unread,
Sep 24, 2016, 7:57:09 AM9/24/16
to Sequelize

Maybe i just stupid, sorry for that. have 2 n:m related tables:

first:

ticket = sequelize.define('ticket', {
        tt_id: {
            field: "tt_id",
            type: Sequelize.INTEGER,
            autoIncrement: true,
            primaryKey: true
        },
        text_01: {
            field: "tt_title",
            type: Sequelize.CHAR(100)
        }
    }, {
        classMethods: {
            associate: function(models) {                    
                this.belongsToMany(models.ticket_type, {
                    through: {
                        model: models.ticket_type_link
                    },
                    as: "tt_type",

                    name: {
                        singular: "tt_type",
                        plural: "tt_type"
                    },
                    foreignKey: "tt_id"
                });
            }
        }
    });

second:

ticketType = sequelize.define('ticket_type', {
      tt_type_id: {
          type: Sequelize.INTEGER,
          autoIncrement: true,
          primaryKey: true
      },
      tt_type_name: Sequelize.CHAR(100)
  }, {
      classMethods: {
          associate: function(models) {
              this.belongsToMany(models.ticket, {
                      through: {
                          model: models.ticket_type_link
                      },
                      foreignKey: "tt_type_id"
                  })                  
          }
      }
  });

and "link" model:

ticketTypeLink = sequelize.define('ticket_type_link', {
        tt_type_link_id: {
            type: Sequelize.INTEGER,
            autoIncrement: true,
            primaryKey: true
        },
        tt_type_id: Sequelize.INTEGER,
        tt_id: Sequelize.INTEGER
    });

I'm trying create new ticket and link it with some types like this:

newRecord = db.ticket.build(val, {
        include: [{
            all: true
        }]
    });

and set linked types with: newRecord.set("tt_type",[{tt_type_id:1},{tt_type_id:2}]); (it works for 1:1 associations and, i think, will work for 1:n).

But when i call newRecord.save() sequelize trying insert new records into ticket_type instead of (or before, may be) insert tt_id and tt_type_id into ticket_type_link.

what am I doing wrong?

Reply all
Reply to author
Forward
0 new messages