如何使用sequelize在beforeBulkUpdate钩子中分配或更新值

问题描述 投票:0回答:2

我正在尝试使用 beforeBulkUpdate 挂钩更新数据库实例,该挂钩被触发,但它不会更新值

这是我的更新实例

let order = await Order.update(
          {
            total_days: literal(`total_days + ${days}`),
          },
          {
            where: { UserId, order_name },
          }
        );

这是我的钩子

beforeBulkUpdate(order, option) {
          if (order.total_days > 2) {
            order.discount = order.total_due * 0.15;
          } else {
            order.discount = 0;
          }
          order.tax = 0.1 * order.total_due;
          order.total_due = order.total_due - order.discount + order.tax;
        }

我做错了吗?还是无法更新 beforeUpdate 挂钩上的值?

node.js sequelize.js
2个回答
0
投票

您在函数中设置值的方式是错误的。您需要使用sequelize model.setDataValue('field-name', value) 函数。

beforeBulkUpdate(order, option) {
    if (order.total_days > 2) {
        order.setDataValue('discount', (order.total_due * 0.15));
    } else {
        order.setDataValue('discount', 0);
    }
    order.setDataValue('tax', (0.1 * order.total_due));
    order.setDataValue('total_due', (order.total_due - order.discount + order.tax));
}

0
投票

假设您使用的是sequelize v6(这是我测试的地方):

您可以通过以下方式更新属性:

beforeBulkUpdate(options) {
    options.attributes.fieldName = fieldValue;
    
    if (options.fields.indexOf('fieldName') === -1) {
        options.fields.push('fieldName');
    }
}

因此您可以更改选项中的属性及其值,但您需要确保这些字段也包含在 options.fields 中,否则更改将被忽略。

不确定这对您是否有帮助,因为total_days是一个文字,因为它是在您的数据库中评估的,而不是续集挂钩本身!

您也无法从正在批量更新的实体中读取值(这意味着:您无法使用

total_due
等进行计算),但您也可以将其作为文字语句传递给数据库。

最后,您应该问自己,beforeBulkUpdate 挂钩是否适合进行此操作。您也可以使用数据库触发器来向您展示替代选项。

© www.soinside.com 2019 - 2024. All rights reserved.