简体   繁体   中英

Select parent model with child model attribute and destroy it - sequelize/MySQL

I have User and VerifyToken model with token and user_id attributes. I need to select an user, but with token (from tokens table) value.

I have tried:

 await models.User.destroy({
    hierarchy: true,

   where: {
    token: token
   }
});

This is User model:

const VerifyToken = require('./verifyToken');

module.exports = (sequelize, DataTypes) => {
const User = sequelize.define('User', {
    password: DataTypes.STRING,
    email: DataTypes.STRING,

}, {
    tableName: 'users',
    //syncOnAssociation: true
    hierarchy: true
});

User.associate = function (models) {
    const {VerifyToken} = models;

    User.hasOne(VerifyToken, {
        onDelete: 'CASCADE'
    });
};

return User;
};

And VerifyToken model:

const User = require('./user');

module.exports = (sequelize, DataTypes) => {
const VerifyToken = sequelize.define('VerifyToken', {

    user_id: DataTypes.INTEGER,
    token: DataTypes.STRING,

}, {
    tableName: 'verify_tokens',
    syncOnAssociation: true,
    hierarchy: true
});


  VerifyToken.associations = function (models) {
    const {User} = models;

    VerifyToken.belongsTo(User);
   };

    return VerifyToken;
};

The problem is that, I even don't know where to start. I have tried with include:[{model: models.VerifyToken, where: {}}] , but how to use user_id called from the child model?

What I want is to select an user (parent model) with a value (token in child model) and delete it with one query.

The problem statement you want is to support join and delete in one sequelize operation.

What I want is to select an user (parent model) with a value (token in child model) and delete it with one query.

In sequelize documenation, Model.destroy has no include in the options property.

So the only left option is to select the user_id 's from VerifyToken model, then call destroy on User model, where id in user_id got from VerifyToken .

In code it will look like following

const verifyTokens = await VerifyToken.findAll({
   where: {
       token: {
           [Sequelize.Op.In] : YOUR_TOKENS_FOR_WHICH_YOU_WANT_TO_DELETE_YOUR_USER
       }
   }
}

const userIdsToDestroy = verifyTokens.map(verifyToken => verifyToken.user_id)
await User.destroy({
    where: {
        id: {
            [Sequelize.Op.in] : userIdsToDestroy
        }
    }
}

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