如果不存在,不确定如何添加记录 jaydata sqllite



我正在尝试完成以下任务。 我有一个从远程数据库返回的 json 数组,我想迭代它,检查本地数据库中是否存在具有对象 ID 的记录。 如果存在,我想更新记录,如果没有,我想附加它。 代码如下:

$.each(data, function(idx, task) { 
                        var taskToUpdate = $org.context.Task.attachOrGet({ Id:task.TaskId});                        
                        taskToUpdate.TaskType = task.TaskType;
                        taskToUpdate.StatusId = task.TaskStatusId;
                        taskToUpdate.TaskStatus = task.TaskStatus;
                        taskToUpdate.DateScheduled = task.Date;
                        taskToUpdate.TimeSlot = task.Time;
                        taskToUpdate.LastUpdated = new Date();
                        taskToUpdate.TaskName = "Job " + task.TaskId + " " + task.TaskType + " @" + task.AddressOfTask + ", " + task.PropertyPostCode;
                        taskToUpdate.SpecialInstructions = task.SpecialInstructions;
                        taskToUpdate.PropertyAddress = task.AddressOfTask;
                        taskToUpdate.PropertyPostCode = task.PropertyPostCode;
                        taskToUpdate.PropertyType = task.PropertyType;
                        taskToUpdate.NumberOfBedrooms = task.NumberOfBedrooms;
                        taskToUpdate.HasGarage = task.HasGarage;
                        taskToUpdate.HasOutHouse = task.HasOutHouse;

                    });
                    $org.context.saveChanges({
                        success: function(db) {
                            that.messages.push("Tasks saved to local device.");
                        }, error: function(err) {
                            console.log(err);
                            that.messages.push("Errors saving tasks: " + err);
                            navigator.notification.alert("Error saving local tasks to your device!",
                                                         function () {
                                                         }, "Error", 'OK');
                        }
                    });  

代码成功执行,但未向任务表添加任何记录。

我错过了什么吗?

我使用了这段代码,它似乎有效,但感觉不"正确"。 即我检测更新是否已完成以避免调用 context.savechanges() 多个更新的方式。 请随时改进我的答案!

function downloadTasksFromWeb(viewModel){
    $org.context.UserSetting.first().then(function (userSetting) {
                viewModel.set("currentUserSettings", userSetting);          
                backofficeUrl = viewModel.get("currentUserSettings.BackOfficeUrl") + "/api/tasks";
                var operatorId = viewModel.get("currentUserSettings.OperatorId");
                var rowsToProcess = 0, rowsProcessed = 0;
                viewModel.messages.push("Connecting to server.");
                showNotificationInfo("Connecting to server.");
                jQuery.ajax({
                    type: "GET",
                    url: backofficeUrl,
                    dataType: 'json',
                    async: false,
                    username: "user",
                    password: "pw",
                    data: {"operatorId": operatorId},
                    success: function (data) {
                        viewModel.messages.push("Tasks received, saving to local device.");
                        showNotificationInfo("Tasks received, saving to local device.");
                        rowsToProcess = data.length;
                        $.each(data, function(idx, task) { 
                            var existingTasks = $org.context.Task.filter("Id", "==", task.TaskId).toArray();
                            existingTasks.then(function(result) {
                                var taskToUpdate = $org.context.Task.attachOrGet({ Id:task.TaskId});
                                taskToUpdate.TaskType = task.TaskType;
                                taskToUpdate.StatusId = task.TaskStatusId;
                                taskToUpdate.TaskStatus = task.TaskStatus;
                                taskToUpdate.DateScheduled = task.Date;
                                taskToUpdate.TimeSlot = task.Time;
                                taskToUpdate.LastUpdated = new Date();
                                taskToUpdate.TaskName = "Job " + task.TaskId + " " + task.TaskType + " @" + task.AddressOfTask + ", " + task.PropertyPostCode;
                                taskToUpdate.SpecialInstructions = task.SpecialInstructions;
                                taskToUpdate.PropertyAddress = task.AddressOfTask;
                                taskToUpdate.PropertyPostCode = task.PropertyPostCode;
                                taskToUpdate.PropertyType = task.PropertyType;
                                taskToUpdate.NumberOfBedrooms = task.NumberOfBedrooms;
                                taskToUpdate.HasGarage = task.HasGarage;
                                taskToUpdate.HasOutHouse = task.HasOutHouse;
                                if (result.length == 0) {
                                    $org.context.Task.add(taskToUpdate);
                                }
                                rowsProcessed++;
                                if (rowsProcessed == rowsToProcess) {
                                    $org.context.saveChanges({
                                        success: function(db) {
                                            viewModel.messages.push("Tasks saved to local device.");
                                            showNotificationInfo("Tasks saved to local device.");
                                        }, error: function(err) {
                                            console.log(err);
                                            viewModel.messages.push("Errors saving tasks: " + err);
                                            showNotificationError("Errors saving tasks: " + err);                                            
                                        }
                                    });  
                                }
                            });
                        });
                    }
                }).fail(function(resultData) {
                    showNotificationError("There was an error communicating with the server.  Please check your settings and try again.");
                });
            });
} 

代替 $.each,您需要一个具有以下算法的递归函数:- 检查是否有任何记录保存到本地数据库的特定ID

  • 如果是
    • 附加
    • 设置属性
  • 如果否
    • 创建新的类型化元素实体
    • 设置属性
    • 将实体添加到集合 - C ontext.Tasks.add(newEntity)
  • 完成所有代码,调用 context.saveChanges( ) 以批量保存所有更改。这比在foreach中调用saveChanes()的代码更快,更安全。

由于异步行为,递归函数是必需的。

相关内容

  • 没有找到相关文章

最新更新