Upgrade to ExtJS 4.0.0 - Released 04/26/2011
[extjs.git] / docs / source / Association.html
1 <!DOCTYPE html><html><head><title>Sencha Documentation Project</title><link rel="stylesheet" href="../reset.css" type="text/css"><link rel="stylesheet" href="../prettify.css" type="text/css"><link rel="stylesheet" href="../prettify_sa.css" type="text/css"><script type="text/javascript" src="../prettify.js"></script></head><body onload="prettyPrint()"><pre class="prettyprint"><pre><span id='Ext-data.Association-method-constructor'><span id='Ext-data.Association'>/**
2 </span></span> * @author Ed Spencer
3  * @class Ext.data.Association
4  * @extends Object
5  *
6  * &lt;p&gt;Associations enable you to express relationships between different {@link Ext.data.Model Models}. Let's say we're
7  * writing an ecommerce system where Users can make Orders - there's a relationship between these Models that we can
8  * express like this:&lt;/p&gt;
9  *
10 &lt;pre&gt;&lt;code&gt;
11 Ext.define('User', {
12     extend: 'Ext.data.Model',
13     fields: ['id', 'name', 'email'],
14
15     hasMany: {model: 'Order', name: 'orders'}
16 });
17
18 Ext.define('Order', {
19     extend: 'Ext.data.Model',
20     fields: ['id', 'user_id', 'status', 'price'],
21
22     belongsTo: 'User'
23 });
24 &lt;/code&gt;&lt;/pre&gt;
25  *
26  * &lt;p&gt;We've set up two models - User and Order - and told them about each other. You can set up as many associations on
27  * each Model as you need using the two default types - {@link Ext.data.HasManyAssociation hasMany} and
28  * {@link Ext.data.BelongsToAssociation belongsTo}. There's much more detail on the usage of each of those inside their
29  * documentation pages. If you're not familiar with Models already, {@link Ext.data.Model there is plenty on those too}.&lt;/p&gt;
30  *
31  * &lt;p&gt;&lt;u&gt;Further Reading&lt;/u&gt;&lt;/p&gt;
32  *
33  * &lt;ul style=&quot;list-style-type: disc; padding-left: 20px;&quot;&gt;
34  *   &lt;li&gt;{@link Ext.data.HasManyAssociation hasMany associations}
35  *   &lt;li&gt;{@link Ext.data.BelongsToAssociation belongsTo associations}
36  *   &lt;li&gt;{@link Ext.data.Model using Models}
37  * &lt;/ul&gt;
38  * 
39  * &lt;b&gt;Self association models&lt;/b&gt;
40  * &lt;p&gt;We can also have models that create parent/child associations between the same type. Below is an example, where
41  * groups can be nested inside other groups:&lt;/p&gt;
42  * &lt;pre&gt;&lt;code&gt;
43
44 // Server Data
45 {
46     &quot;groups&quot;: {
47         &quot;id&quot;: 10,
48         &quot;parent_id&quot;: 100,
49         &quot;name&quot;: &quot;Main Group&quot;,
50         &quot;parent_group&quot;: {
51             &quot;id&quot;: 100,
52             &quot;parent_id&quot;: null,
53             &quot;name&quot;: &quot;Parent Group&quot;
54         },
55         &quot;child_groups&quot;: [{
56             &quot;id&quot;: 2,
57             &quot;parent_id&quot;: 10,
58             &quot;name&quot;: &quot;Child Group 1&quot;
59         },{
60             &quot;id&quot;: 3,
61             &quot;parent_id&quot;: 10,
62             &quot;name&quot;: &quot;Child Group 2&quot;
63         },{
64             &quot;id&quot;: 4,
65             &quot;parent_id&quot;: 10,
66             &quot;name&quot;: &quot;Child Group 3&quot;
67         }]
68     }
69 }
70
71 // Client code
72 Ext.define('Group', {
73     extend: 'Ext.data.Model',
74     fields: ['id', 'parent_id', 'name'],
75     proxy: {
76         type: 'ajax',
77         url: 'data.json',
78         reader: {
79             type: 'json',
80             root: 'groups'
81         }
82     },
83     associations: [{
84         type: 'hasMany',
85         model: 'Group',
86         primaryKey: 'id',
87         foreignKey: 'parent_id',
88         autoLoad: true,
89         associationKey: 'child_groups' // read child data from child_groups
90     }, {
91         type: 'belongsTo',
92         model: 'Group',
93         primaryKey: 'id',
94         foreignKey: 'parent_id',
95         autoLoad: true,
96         associationKey: 'parent_group' // read parent data from parent_group
97     }]
98 });
99
100
101 Ext.onReady(function(){
102     
103     Group.load(10, {
104         success: function(group){
105             console.log(group.getGroup().get('name'));
106             
107             group.groups().each(function(rec){
108                 console.log(rec.get('name'));
109             });
110         }
111     });
112     
113 });
114  * &lt;/code&gt;&lt;/pre&gt;
115  *
116  * @constructor
117  * @param {Object} config Optional config object
118  */
119 Ext.define('Ext.data.Association', {
120 <span id='Ext-data.Association-cfg-ownerModel'>    /**
121 </span>     * @cfg {String} ownerModel The string name of the model that owns the association. Required
122      */
123
124 <span id='Ext-data.Association-cfg-associatedModel'>    /**
125 </span>     * @cfg {String} associatedModel The string name of the model that is being associated with. Required
126      */
127
128 <span id='Ext-data.Association-cfg-primaryKey'>    /**
129 </span>     * @cfg {String} primaryKey The name of the primary key on the associated model. Defaults to 'id'.
130      * In general this will be the {@link Ext.data.Model#idProperty} of the Model.
131      */
132     primaryKey: 'id',
133
134 <span id='Ext-data.Association-cfg-reader'>    /**
135 </span>     * @cfg {Ext.data.reader.Reader} reader A special reader to read associated data
136      */
137     
138 <span id='Ext-data.Association-cfg-associationKey'>    /**
139 </span>     * @cfg {String} associationKey The name of the property in the data to read the association from.
140      * Defaults to the name of the associated model.
141      */
142
143     defaultReaderType: 'json',
144
145     statics: {
146         create: function(association){
147             if (!association.isAssociation) {
148                 if (Ext.isString(association)) {
149                     association = {
150                         type: association
151                     };
152                 }
153
154                 switch (association.type) {
155                     case 'belongsTo':
156                         return Ext.create('Ext.data.BelongsToAssociation', association);
157                     case 'hasMany':
158                         return Ext.create('Ext.data.HasManyAssociation', association);
159                     //TODO Add this back when it's fixed
160 //                    case 'polymorphic':
161 //                        return Ext.create('Ext.data.PolymorphicAssociation', association);
162                     default:
163                         //&lt;debug&gt;
164                         Ext.Error.raise('Unknown Association type: &quot;' + association.type + '&quot;');
165                         //&lt;/debug&gt;
166                 }
167             }
168             return association;
169         }
170     },
171
172     constructor: function(config) {
173         Ext.apply(this, config);
174
175         var types           = Ext.ModelManager.types,
176             ownerName       = config.ownerModel,
177             associatedName  = config.associatedModel,
178             ownerModel      = types[ownerName],
179             associatedModel = types[associatedName],
180             ownerProto;
181
182         //&lt;debug&gt;
183         if (ownerModel === undefined) {
184             Ext.Error.raise(&quot;The configured ownerModel was not valid (you tried &quot; + ownerName + &quot;)&quot;);
185         }
186         if (associatedModel === undefined) {
187             Ext.Error.raise(&quot;The configured associatedModel was not valid (you tried &quot; + associatedName + &quot;)&quot;);
188         }
189         //&lt;/debug&gt;
190
191         this.ownerModel = ownerModel;
192         this.associatedModel = associatedModel;
193
194 <span id='Ext-data.Association-property-ownerName'>        /**
195 </span>         * The name of the model that 'owns' the association
196          * @property ownerName
197          * @type String
198          */
199
200 <span id='Ext-data.Association-property-associatedName'>        /**
201 </span>         * The name of the model is on the other end of the association (e.g. if a User model hasMany Orders, this is 'Order')
202          * @property associatedName
203          * @type String
204          */
205
206         Ext.applyIf(this, {
207             ownerName : ownerName,
208             associatedName: associatedName
209         });
210     },
211
212 <span id='Ext-data.Association-method-getReader'>    /**
213 </span>     * Get a specialized reader for reading associated data
214      * @return {Ext.data.reader.Reader} The reader, null if not supplied
215      */
216     getReader: function(){
217         var me = this,
218             reader = me.reader,
219             model = me.associatedModel;
220
221         if (reader) {
222             if (Ext.isString(reader)) {
223                 reader = {
224                     type: reader
225                 };
226             }
227             if (reader.isReader) {
228                 reader.setModel(model);
229             } else {
230                 Ext.applyIf(reader, {
231                     model: model,
232                     type : me.defaultReaderType
233                 });
234             }
235             me.reader = Ext.createByAlias('reader.' + reader.type, reader);
236         }
237         return me.reader || null;
238     }
239 });
240 </pre></pre></body></html>