【问题标题】:Multiple images + Node.js + Sequelize + Mysql多张图片 + Node.js + Sequelize + Mysql
【发布时间】:2021-09-13 04:44:56
【问题描述】:

我想在 Sequelize + node.js 和 MySQL 数据库中建立一个关联,其中 Product.hasMany(images)images.belongsTo(Product)。我想上传多张图片到数据库。

我已完成将多个图像上传到 AWS S3。但我想将这些图像的返回链接存储到数据库中。我无法处理这种关系,因为我无法同时将所有图像的链接添加到数据库。我想要的只是将不同的图像连同它所属的产品 ID 添加到表的每一行。

【问题讨论】:

    标签: mysql node.js express orm sequelize.js


    【解决方案1】:

    我不确定 AWS S3 如何上传文件(图像),但我认为逻辑与以下相同

    let images = [];
    // to see if files field exist
    if(req.files) {
      // logic to save url in db
      for (let i=0; i < req.files.length; i++) {
        let image = await Image.create(req.files[i])
        images.push(image)
      }
    } 
    // will assume req.body has required fields
    const product = await Product.create(req.body)
    // here use association mixins
    await product.addImages(images);
    

    要了解有关关联混合的更多信息,请查看此链接stackoverflow-question-about-sequelize-mixins

    【讨论】:

    • 感谢您的回复,效果很好?
    猜你喜欢
    • 2018-12-31
    • 2013-11-03
    • 1970-01-01
    • 1970-01-01
    • 2016-09-07
    • 2017-03-21
    • 2011-04-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多