【问题标题】:Android: work with Parse database for an IncrementKey column at ParseAndroid:在 Parse 使用 Parse 数据库获取 IncrementKey 列
【发布时间】:2014-11-29 06:24:47
【问题描述】:

我正在开发一个 Android 应用程序并且正在使用 Parse 数据库,并且想添加一个 IncrementKey 函数,以便在将新图像添加到数据库时,image_id 列会增加 1。

参考:https://www.parse.com/questions/incrementkey

问题:

然而,谷歌搜索了很长时间,没有明确的例子来展示如何让它工作......它涉及解析时的云代码。是否有任何关于如何做到这一点的提示?

谢谢!

【问题讨论】:

  • 云代码易于实现。有什么问题?
  • 我对此一无所知...你有例子吗?
  • 他们有一个可以帮助你的指南。它基本上是 JavaScript 代码。您可以获得大量关于它的教程。

标签: android database parse-platform cloud auto-increment


【解决方案1】:

Image 创建一个 beforeSave 触发器(在相关的地方替换,我假设这是你的类,它包含图像和计数器列 - 这些是同一个对象的属性)

文件:./cloud_code/cloud/main.js 或文件路径 required by main.js

Parse.Cloud.beforeSave("Image", function(request, response) {

    //check if this is a new or existing Image
    if (!request.object.isNew()) {
          //image exists, save as normal
          response.success();
    } else { 

        //find the last image saved
        var checkImage = Parse.Object.extend("Image");
        var imagesQuery = new Parse.Query(checkImage);
        imagesQuery.select("image_id"); //save memory by only requesting image_id
        imagesQuery.descending("image_id"); //sort, make sure image_id is a Number

        imagesQuery.first().then(
            function(lastImage) {
                //increase the id by 1
                var newId = lastImage.get("image_id") + 1;

                //save the current object with the new id
                request.object.set("image_id", newId); 
                response.success(); //this saves your request.object
            }, 
            function (error)
                response.error(error);
            }
        );

    }

});

资源

阅读 Cloud 代码指南,了解如何使用安装 CLI 工具以部署您的云代码并检查云日志以进行调试。

  • 免责声明:以上代码未经测试,但基于工作功能

注意:beforeSave 处理程序中使用isNew(),在afterSave 处理程序中使用existed。在 Parse Cloud Code 版本 1.6 中报告了 existed 的错误。* - 请参阅 Parse request.object.existed() return false

【讨论】:

  • 请注意,解析对象的唯一 ID 为 objectIdimage.id。云代码功能在调用reponse.success时保存,普通控制器应使用imageCounts.save();您可以使用imageCounts.increment("image_count")增加一个现有数字字段
猜你喜欢
  • 2018-09-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-10-29
  • 1970-01-01
  • 2023-03-20
相关资源
最近更新 更多