sails.js – 使用SailsJS一次更新多条记录

栏目: 数据库 · 发布时间: 5年前

内容简介:翻译自:https://stackoverflow.com/questions/26952705/update-multiple-records-at-once-using-sailsjs

所以我正在制作这个应用程序,我会为餐厅提供菜单项吗?

所有者应该能够移动菜单项

这是我的menuitem.js模型包含的

名称,价格,位置

而已.超级简单.

因此,为了重新定位这些元素,我将使用jquery UI

所以最终产品将与此非常相似> http://jqueryui.com/sortable/

因此,我的目标是每次更改其中一个菜单项时,将每个菜单项的位置保存在数据库中.所以我认为Sails必须有一个可以一次更新所有记录的功能

如下

Menuitem.update([{id: 1},{position: 3}], [{id: 2},{position: 3}] ).exec(function(err, updatedRecords) {
            if (err) {
                return res.send({message: 'Could not update the records', err: err}, 500);
            }

            if (updatedRecords) {
                return res.send({ records: updatedRecords }, 200);
            } else {
                return res.notFound('Records not found');
            }
        });

任何帮助将不胜感激

还在SailsJS上打开了一个问题

https://github.com/balderdashy/sails/issues/2404

您可以使用本机 SQL 查询来实现此目的.要执行本机SQL查询,您需要使用waterline的Model.query()函数.在你的情况下,它将是这样的.

var myQuery = "update menuitem set ....   complete SQL query goes here ";

Menuitem.query(myQuery, function (err, result){
  if(err){
    // error handling here
  }
  else{
    // do something with result here
  }
});

现在,对于本机SQL查询,可以使用case语句根据位置值更新行.例如,如果我将项目从位置4移动到位置2,那么我的查询将是这样的.

update menuitem
set position = case when position = 4 then 2
               when position >=2 then position + 1 
               else position end;

当然,4和2将动态提供,您的查询可能看起来更复杂,因为您还需要处理用户是向上还是向下移动对象.但这就是你如何实现这一目标的方法.如果需要执行更复杂的逻辑,也可以创建存储过程.这也将通过使用Model.query来执行.使用最终用户提供的参数构建动态查询时要小心SQL注入攻击.

翻译自:https://stackoverflow.com/questions/26952705/update-multiple-records-at-once-using-sailsjs


以上所述就是小编给大家介绍的《sails.js – 使用SailsJS一次更新多条记录》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

HTTP Developer's Handbook

HTTP Developer's Handbook

Chris Shiflett / Sams Publishing / 2003-3-29 / USD 39.99

The largest group with an unsatisfied demand for a good book on HTTP is the worldwide group of Web developers. A good book on HTTP can help new and old Web developers alike, as a thorough understandin......一起来看看 《HTTP Developer's Handbook》 这本书的介绍吧!

HTML 压缩/解压工具
HTML 压缩/解压工具

在线压缩/解压 HTML 代码

图片转BASE64编码
图片转BASE64编码

在线图片转Base64编码工具