* Delete multiple instances, or set their deletedAt timestamp to the current time if `paranoid` is enabled. * * @param {object} options destroy options * @param {object} [options.where] Filter the destroy * @param {boolean} [opt
(options)
| 3018 | * @returns {Promise<number>} The number of destroyed rows |
| 3019 | */ |
| 3020 | static async destroy(options) { |
| 3021 | options = Utils.cloneDeep(options); |
| 3022 | |
| 3023 | // Add CLS transaction |
| 3024 | if (options.transaction === undefined && this.sequelize.constructor._cls) { |
| 3025 | const t = this.sequelize.constructor._cls.get('transaction'); |
| 3026 | if (t) { |
| 3027 | options.transaction = t; |
| 3028 | } |
| 3029 | } |
| 3030 | |
| 3031 | this._injectScope(options); |
| 3032 | |
| 3033 | if (!options || !(options.where || options.truncate)) { |
| 3034 | throw new Error('Missing where or truncate attribute in the options parameter of model.destroy.'); |
| 3035 | } |
| 3036 | |
| 3037 | if (!options.truncate && !_.isPlainObject(options.where) && !Array.isArray(options.where) && !(options.where instanceof Utils.SequelizeMethod)) { |
| 3038 | throw new Error('Expected plain object, array or sequelize method in the options.where parameter of model.destroy.'); |
| 3039 | } |
| 3040 | |
| 3041 | options = _.defaults(options, { |
| 3042 | hooks: true, |
| 3043 | individualHooks: false, |
| 3044 | force: false, |
| 3045 | cascade: false, |
| 3046 | restartIdentity: false |
| 3047 | }); |
| 3048 | |
| 3049 | options.type = QueryTypes.BULKDELETE; |
| 3050 | |
| 3051 | Utils.mapOptionFieldNames(options, this); |
| 3052 | options.model = this; |
| 3053 | |
| 3054 | |
| 3055 | // Run before hook |
| 3056 | if (options.hooks) { |
| 3057 | await this.runHooks('beforeBulkDestroy', options); |
| 3058 | } |
| 3059 | let instances; |
| 3060 | // Get daos and run beforeDestroy hook on each record individually |
| 3061 | if (options.individualHooks) { |
| 3062 | instances = await this.findAll({ where: options.where, transaction: options.transaction, logging: options.logging, benchmark: options.benchmark }); |
| 3063 | |
| 3064 | await Promise.all(instances.map(instance => this.runHooks('beforeDestroy', instance, options))); |
| 3065 | } |
| 3066 | let result; |
| 3067 | // Run delete query (or update if paranoid) |
| 3068 | if (this._timestampAttributes.deletedAt && !options.force) { |
| 3069 | // Set query type appropriately when running soft delete |
| 3070 | options.type = QueryTypes.BULKUPDATE; |
| 3071 | |
| 3072 | const attrValueHash = {}; |
| 3073 | const deletedAtAttribute = this.rawAttributes[this._timestampAttributes.deletedAt]; |
| 3074 | const field = this.rawAttributes[this._timestampAttributes.deletedAt].field; |
| 3075 | const where = { |
| 3076 | [field]: Object.prototype.hasOwnProperty.call(deletedAtAttribute, 'defaultValue') ? deletedAtAttribute.defaultValue : null |
| 3077 | }; |