I am using sql adapter to work with a database. What is the proper way to handle updates?
The code below adds 1 point correctly to the sum_points field in the database of the entry with questionid 1624 , but there is also an error message (rs.fieldCount) coming up and console.log at the end is not executed
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 (in models folder)
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;
},
Labels in the Scrollview (that are populated by the database) are created programmatically.
SOLUTION
Added the model src in the .xml file and fetch and set the values as Rene suggested:
<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();
You appear to be using collections and models, and not just a database. For most important things you don't need to use queries at all. Just look at the related docs regarding models.
In your case, just get the model with a proper ID (or any backbone method to get them)
var model = $.fetchedTranslations.get('123');
model.set({sum_points: model.get('sum_points') + 1});
model.save();
Since collections are backbone based, I recommend checking the backbone docs too, so you can see how you can get by any other properties besides ID, filter, etc.