使用sequelize多次更新同一行的正确方法

编程入门 行业动态 更新时间:2024-10-09 17:25:28

使用sequelize多次更新同一行的<a href=https://www.elefans.com/category/jswz/34/1771142.html style=正确方法"/>

使用sequelize多次更新同一行的正确方法

我有一个order表,我想“再次购买”,order表包含一列productDetails。在此列中,我有一个带有products的数组。

要执行此“再次购买”操作,我需要将相同的数组放入购物车中。及时更新重要信息(检查是否有库存,产品是否在目录中处于活跃状态等),对于阵列中的每个产品,我都会在购物车表上进行更新,基本上,我将尝试以下操作:

我正在使用node.jssequelize.js来做到这一点:

// Get the older order
const order = await Order.findOne({
    include: [
        {
            model: OrderProduct,
        },
    ],
    where: {
        orderId,
    },
});

// If the cart have something inside, clean the cartDetails column
await CartService.clean(order.userId);

// The addProduct do the checks and insert the product inside the cart
await Promise.all(
    order.OrderProducts.map(async data => {
        await CartService.addProduct(order.userId, data.productMarketId, data.quantity);
    })
);

也许addProduct仅插入一种产品。如果还有更多产品,则地图可以正确执行,但列表中仅添加了一种产品。

[当我在调试中运行时,首先代码在addProduct()上调用两次(当我的订单上有两个产品时),因此,获得购物车数据的选择始终为空,并且仅正确插入了最后一个产品。

使用2种产品的预期行为:

1. clean cart
2. enter on iterator (map or something else) (product 0):

  2.1. Select cart details (which is empty on first time)
  2.2. Insert product on cart

3. next item on iterator (product 1)

  3.1. Select cart details (which have one element)
  3.2. Insert product on cart

3. end of iterator with 2 products registered on my database.

发生了什么:


1. clean cart
2. enter on iterator (map or something else):
  2.1.a. get the empty cart
  2.1.b. get the empty cart again
  2.2.a. update the product 0 on empty cart selected in 2.1.a. (following the stack of (a)
  2.2.b. update the product 1 on empty cart selected in 2.1.b. (following the stack of (b)

3. Return the cart with only one product inside (the last product).

EDIT:我制作了关于该行为的视频:video here

还有原始的addProduct函数(使用async),并在第一个await上并行化(我在某些地方放了/ * ... * /以使问题变小:]]]

  async addProduct(userId, productMarketId, quantity) {
        const productMarketData = await roductMarket.findByPk(productMarketId, { /* ... */ });


        const productKey = Buffer.from(PHPSerialize.serialize(`SP_${productMarketId}`)).toString('base64');

        if (!cart) {
            cart = await this.clean(userId);
        }

        // ...

        const newCart = await Cart.upsert({ /* ... */ }).then(result => {
            return result.cartUserId;
        });
        return newCart;
    }

这种行为与诺言有关吗?还是异步/等待行为?谢谢。

我有一个订单表,我想“再次购买”,该订单表包含一列productDetails。在此列中,我有一个包含产品的数组。要执行此“再次购买”操作,我需要将...

回答如下:

Array.map不适用于异步功能,因此您应该将Promise.all调用修改为以下内容:

更多推荐

使用sequelize多次更新同一行的正确方法

本文发布于:2024-05-07 14:23:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1756664.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:正确   方法   sequelize

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!