PDA

View Full Version : Sencha model: relations



MartijnD
21 Jun 2011, 5:31 AM
Hi,

I believe the model part of sencha touch is very powerfull, but I just can't get it to work. I'm currently using the following code in my playground. It consists of two models (Chapter and Subject) with each its own store. One Chapter can contain multiple subjects and one Subject belongs to one Chapter. I've defined these associations in my models. In the application launch method, I try to retreive all subjects of the first chapter, but it returns an empty list of subjects. Anyone got a clue?


console.log(chapters.getAt(0).subjects().data);



<!DOCTYPE html>
<html>
<head>
<title>Playground</title>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8">

<script type="text/javascript" src="lib/touch/sencha-touch-debug.js"></script>
<link href="lib/touch/resources/css/sencha-touch.css" rel="stylesheet" type="text/css" />

<script type="text/javascript">
Ext.regModel("Chapter", {
fields: [
{name: "id", type: "int"},
{name: "name", type: "string"},
{name: "description", type: "string"}
],

associations: [
{type: 'hasMany', model: 'Subject', name: 'subjects'}
],

proxy: {
type: 'rest',
url: 'chapters.php',
reader: {
type: 'json',
root: 'chapters'
}
}
});

Ext.regModel("Subject", {
fields: [
{name: "id", type: "int"},
{name: "chapter_id", type: "int"},
{name: "name", type: "string"}
],

associations: [
{type: 'belongsTo', model: 'Chapter'}
],

proxy: {
type: 'rest',
url: 'subjects.php',
reader: {
type: 'json',
root: 'subjects'
}
}
});

chapters = new Ext.data.Store({
model: 'Chapter',
data : [
{id: '1', name: 'Hoofdstuk 1', description: 'Hoofdstuk 1 desc'},
{id: '2', name: 'Hoofdstuk 2', description: 'Hoofdstuk 2 desc'}
]
});

subjects = new Ext.data.Store({
model: 'Subject',
data : [
{id: '1', chapter_id: '1', name: 'Subject 1'},
{id: '2', chapter_id: '1', name: 'Subject 2'},
{id: '3', chapter_id: '2', name: 'Subject 3'},
{id: '4', chapter_id: '2', name: 'Subject 4'}
]
});

new Ext.Application({
launch: function() {
console.log(chapters.getAt(0).subjects().data);
}
});
</script>
</head>

<body>

</body>
</html>

MartijnD
21 Jun 2011, 7:51 AM
Just found a similar question on Stackoverflow (http://stackoverflow.com/questions/6423875/sencha-touch-associated-store-model-pair-not-creating-instance-name-function). Seems like you require to call a load()-method before records are actually loaded. Hope this topic is of any help for Googlers, since I don't think this is well documented. The change to the above code is simply:



new Ext.Application({
launch: function() {
console.log(chapters.getAt(0).subjects().load());
}
});