Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sequelize delete instance with n:m and 1:m associations and update Model

I have 2 models in my postgresql db and using sequelize and node:

  1. Users
  2. Transactions

and are associated like this:

UserModel.hasMany(TransactionModel, { as: 'sentTransactions', foreignKey: 'senderId' });
UserModel.hasMany(TransactionModel, { as: 'receivedTransactions', foreignKey: 'receiverId' });
UserModel.belongsToMany(TransactionModel, { as: 'transactionLikes', through: 'UserLike', foreignKey: 'userId' });
TransactionModel.belongsTo(UserModel, { as: 'receiver' });
TransactionModel.belongsTo(UserModel, { as: 'sender' });
TransactionModel.belongsToMany(UserModel, { as: 'likers', through: 'UserLike', foreignKey: 'transactionId' });

Which means a user has many received and sent transactions and each user can "like" many transactions.

How can I delete a transaction and remove all associations (receiver, sender, liker)? I don't want to delete the users too.

I would also like to update the User Model which is defined like this, in order to add an "email" property:

const UserModel = db.define('user', {
   id: { type: Sequelize.STRING, unique: true, primaryKey: true },
   firstName: { type: Sequelize.STRING  },
   lastName: { type: Sequelize.STRING },
   username: {
    type: Sequelize.STRING,
    unique: {
    args: true,
    msg: USERNAME_IS_TAKEN,
   },
 }

How can I update the model? What will happen to the existing instances?

Thank you in advance for your help!

like image 609
perrosnk Avatar asked Nov 08 '22 04:11

perrosnk


1 Answers

According to this tutorial your M:N relation should work as you expect it out of the box:

For n:m, the default for both is CASCADE. This means, that if you delete or update a row from one side of an n:m association, all the rows in the join table referencing that row will also be deleted or updated.

Further more, to enforce the CASCADE behavior you may also pass onDelete option to the association calls. Something like this should do the trick:

TransactionModel.belongsToMany(UserModel, { as: 'likers', through: 'UserLike', foreignKey: 'transactionId', onDelete: 'CASCADE' });

Adding an email property to the User Model should be as easy as that:

const UserModel = db.define('user', {
    id: {
        type: Sequelize.STRING,
        unique: true,
        primaryKey: true
    },
    firstName: { type: Sequelize.STRING  },
    lastName: { type: Sequelize.STRING },
    username: {
        type: Sequelize.STRING,
        unique: {
            args: true,
            msg: USERNAME_IS_TAKEN,
        }
    },
    email: { type: Sequelize.STRING }
});
like image 196
Boris Schegolev Avatar answered Dec 09 '22 21:12

Boris Schegolev