如何使用 Appcelerator 正确更新 sql 数据库中的值?

How to properly update values in a sql Database with Appcelerator?

我正在使用 sql 适配器来处理数据库。处理更新的正确方法是什么?

下面的代码正确地向 questionid 为 1624 的条目的数据库中的 sum_points 字段添加了 1 点,但也出现了一条错误消息 (rs.fieldCount) 并且 console.log最后不执行

var fetchedTranslations = $.translationData;
fetchedTranslations.fetch({
query: { statement: 'UPDATE "translationsCollection" SET "sum_points" = "sum_points" + ? WHERE "questionid" = ?', params: [1,1624] } //correctly changes the value but results in error message (rs.fieldCount)
});
console.log("fetchedTranslations: " + JSON.stringify(fetchedTranslations));
}

views.xml:

 <Alloy>
<!--<Model src="translationsCollection"/>-->
<Collection src="translationsCollection" instance="true" id="translationData"/>
<Window id="learnQuestions" title="Learn">
<View id="learnQuestionContainer" layout="vertical" width="98%" borderWidth="2" borderRadius="5" backgroundColor="Alloy.CFG.design.backgroundColor" borderColor="#E6000000" height="98%">
    <View id="ratingBar" height="Ti.UI.SIZE" backgroundColor="orange" left="1%" width="98%">
        <Label id="pointsCounter" width="30%" left="30%" height="Ti.UI.SIZE"  top="0" text="pointsCounter" onClick="calculatePoints" top="0"/> 
        <!-- calculatePoints triggers the points update function-->
    </View>
    <ScrollView id="learnQuestionsContainer" layout="vertical" height="Ti.UI.SIZE" dataCollection="$.translationData" dataTransform="transformFunction">
    </ScrollView>
</View>
</Window>

trasnlationCollection.js(在模型文件夹中)

exports.definition = {
config: {
    columns: {
        "questionid": "real",
        "question": "text",
        "answer": "text",
        "difficulty": "real",
        "language": "text",
        "sum_points": "real",
        "sum_words": "real"
    },
    adapter: {
        type: "sql",
        collection_name: "translationsCollection",
        idAttribute : "questionid"
    }
},
extendModel: function(Model) {
    _.extend(Model.prototype, {
        idAttribute : "questionid",
        // extended functions and properties go here
    });
    return Model;
},

滚动视图中的标签(由数据库填充)以编程方式创建。

解决方案

在 .xml 文件中添加了模型 src,并按照 Rene 的建议获取和设置值:

<Model src="translationsCollection"/> 

var fetchedTranslations = $.translationData;
var model = fetchedTranslations.get('1624');
console.log("model fetched: " + JSON.stringify(model));
model.set({sum_points: model.get('sum_points') + 1});
model.save();

您似乎在使用集合和模型,而不仅仅是数据库。对于最重要的事情,您根本不需要使用查询。只需查看有关模型的相关docs

在你的情况下,只需获取具有正确 ID 的模型(或任何 backbone 获取它们的方法)

var model = $.fetchedTranslations.get('123');
model.set({sum_points: model.get('sum_points') + 1});
model.save();

由于集合是基于 backbone 的,我建议也检查 backbone docs,这样您就可以了解如何通过 ID、筛选器等以外的任何其他属性来获取