简体   繁体   中英

Inserting data in multiple tables using Sequelize

It's my first time using Sequelize with MySQL and would like to understand how to insert data into two tables with a foreign key dependency. Let's say, I have two tables - bookingDescription and bookingSummary. The entities for the same are as follows

//bookingSummary
module.exports = (sequelize, DataTypes) => {
    return sequelize.define('bookingSummary', {
        headerId: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true,},
        titleId: DataTypes.STRING,
        abNumber: DataTypes.INTEGER,
        userProfileId: DataTypes.INTEGER,
        theatreId: DataTypes.STRING,
        mFId: DataTypes.STRING,
        createdBy: { type: DataTypes.TEXT, allowNull: false },
        modifiedBy: { type: DataTypes.TEXT, allowNull: false },
        status: DataTypes.STRING
    }, {
        tableName: 'booking_summary',
        underscored: true
    })
}

//bookingDescription 
module.exports = (sequelize, DataTypes) => {
    return sequelize.define('bookingWeek', {
        lineId: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true,},
        headerId: DataTypes.STRING,
        titleId: DataTypes.STRING,
        abNumber: DataTypes.INTEGER,
        theatreId: DataTypes.STRING,
        mFId: DataTypes.STRING,
        theatreName: DataTypes.STRING,
        city: DataTypes.STRING,
        state: DataTypes.STRING,
        playStartDate: DataTypes.DATE,
        playEndDate: DataTypes.DATE,
        preferredFormat: DataTypes.INTEGER,
        screensInDay: DataTypes.INTEGER,
        featureTypeFlag: DataTypes.TEXT,
        cofeatureName: DataTypes.STRING,
        exhbtrReqComment: DataTypes.STRING,
        createdBy: { type: DataTypes.TEXT, allowNull: false },
        modifiedBy: { type: DataTypes.TEXT, allowNull: false },
        status: DataTypes.STRING
    }, {
        tableName: 'booking_description',
        underscored: true
    })
}

Foreign key references in bookingSummary are as follows

FOREIGN KEY (headerId) REFERENCES bookingSummary(headerId)

FOREIGN KEY (titleId, abNumber, mFId)

REFERENCES bookingSummary(abNumber)

I have an object of data which needs to be inserted into the tables at an instant. Any idea on how to approach this?

So, i would recommend you first learning about SQL relations, regardless of Sequelize, and your current project structure, because it seems to me that you still lack the basic understanding of the logic behind these associations, where they should be used and how.

Both your tables have duplicate fields, which makes no sense. Take a look here, for example: https://code.tutsplus.com/articles/sql-for-beginners-part-3-database-relationships--net-8561

As for your current code, i played with it a bit, and this is what i did(will work only if you're using model.sync(), because a column needs to be created automatically. Also use force:true if you already have the tables):

module.exports = (sequelize, DataTypes) => {
    const bookingHeader =  sequelize.define('bookingHeader', {
        id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true},        
        abNumber: DataTypes.INTEGER,
        userProfileId: DataTypes.INTEGER,
        theatreId: DataTypes.STRING,
        mFId: DataTypes.STRING,
        createdBy: { type: DataTypes.TEXT, allowNull: true },
        modifiedBy: { type: DataTypes.TEXT, allowNull: true },
        status: DataTypes.STRING
    }, {
        tableName: 'booking_header',
        // underscored: true
    })

    bookingHeader.associate = function (models) {


        bookingHeader.hasOne(models.bookingDescription);
    };

    return bookingHeader;
}

Booking description:

module.exports = (sequelize, DataTypes) => {
    const bookingDescription = sequelize.define('bookingDescription', {
        id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true, },
        abNumber: DataTypes.INTEGER,
        theatreId: DataTypes.STRING,
        mFId: DataTypes.STRING,
        theatreName: DataTypes.STRING,
        city: DataTypes.STRING,
        state: DataTypes.STRING,
        playStartDate: DataTypes.DATE,
        playEndDate: DataTypes.DATE,
        preferredFormat: DataTypes.INTEGER,
        screensInDay: DataTypes.INTEGER,
        featureTypeFlag: DataTypes.TEXT,
        cofeatureName: DataTypes.STRING,
        exhbtrReqComment: DataTypes.STRING,
        createdBy: { type: DataTypes.TEXT, allowNull: false },
        modifiedBy: { type: DataTypes.TEXT, allowNull: false },
        status: DataTypes.STRING
    }, {
        tableName: 'booking_description',
        // underscored: true
    })

    bookingDescription.associate = function (models) {


        bookingDescription.belongsTo(models.bookingHeader);
    };

    return bookingDescription;
}

In your route, you can do something like this:

  const {bookingHeader,bookingDescription} = models;

  app.post("/booking", async (req, res, next) => {
    try {     
      const header = await bookingHeader.create(req.body)
      const headerId = header.id      
      await bookingDescription.create({state:'active',createdBy:'somebody',modifiedBy:'somebody',bookingHeaderId:headerId})      
      res.json(header);
    } catch (error) {
      console.log(error)
      res.status(500)    
    }
  });

Notice that i hardcoded some of the fields for the description, just for example purposes. Also, it's possible that there is a "better" way to do this with Sequelize, but the docs are really poor, so this gets the job done.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM