【问题标题】:how to dynamically update row in mysql on node express js如何在node express js上动态更新mysql中的行
【发布时间】:2020-12-27 10:54:10
【问题描述】:

这就是我查询更新行的方式,它的工作原理:

const [rows, meta] = await db.query(
        `
        UPDATE
            Portfolio
        SET
            title = ?,
            infoText = ?,
            devPeriod = ?,
            tags = ?
        WHERE
            id = ?
        `,
        [title, infoText, Number(devPeriod), tags, Number(portfolioId)]
    );
    return rows;

但有时取决于用户想要什么,我必须查询才能仅更新特定列。例如,用户可能只想编辑 devPeriod 或标签和 infoText。 我如何做到这一点?

【问题讨论】:

    标签: mysql node.js express mariadb


    【解决方案1】:

    我建议创建一个更新对象来指定要更新的字段和相关值。然后,您可以从中创建查询和参数。

    可以根据用户输入填充更新对象。

    例如:

    async function updatePortfolio(db, portfolioId, update) {
        const query = "Update Portfolio SET " + Object.keys(update).map(key => `${key} = ?`).join(", ") + " WHERE id = ?";
        const parameters = [...Object.values(update), portfolioId];
        console.log("updatePortfolio: Running query:", query);
        const [rows, meta] = await db.query(query, parameters);
        return rows;
    }
    
    // Add or remove fields as you require.
    update = { 
        title: "Some Title",
        infoText: "Infotext",
        devPeriod: 10,
        tags: "tags"
    }
    
    updatePortfolio(db, 1, update);
    
    // Add or remove fields as you require.
    update = { 
        title: "Some Title",
        tags: "tags"
    }
    
    updatePortfolio(db, 2, update);
    

    【讨论】:

      【解决方案2】:

      在向我的同事寻求帮助后,他们向我介绍了 Knex.js,以便更轻松地构建动态查询。所以我就跟着去了。 从那以后一直使用它进行动态查询。非常适合这种类型的任务。配置也很简单:

      import knex from 'knex';
      
      const queryBuilder = knex({ client: 'mysql' });
      
      export default queryBuilder;
      

      导出并在项目中的任何位置使用它

      【讨论】:

        猜你喜欢
        • 2018-03-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-07-13
        • 1970-01-01
        相关资源
        最近更新 更多