Upgrade to ExtJS 4.0.7 - Released 10/19/2011
[extjs.git] / src / data / HasManyAssociation.js
1 /*
2
3 This file is part of Ext JS 4
4
5 Copyright (c) 2011 Sencha Inc
6
7 Contact:  http://www.sencha.com/contact
8
9 GNU General Public License Usage
10 This file may be used under the terms of the GNU General Public License version 3.0 as published by the Free Software Foundation and appearing in the file LICENSE included in the packaging of this file.  Please review the following information to ensure the GNU General Public License version 3.0 requirements will be met: http://www.gnu.org/copyleft/gpl.html.
11
12 If you are unsure which license is appropriate for your use, please contact the sales department at http://www.sencha.com/contact.
13
14 */
15 /**
16  * @author Ed Spencer
17  * @class Ext.data.HasManyAssociation
18  * @extends Ext.data.Association
19  * 
20  * <p>Represents a one-to-many relationship between two models. Usually created indirectly via a model definition:</p>
21  * 
22 <pre><code>
23 Ext.define('Product', {
24     extend: 'Ext.data.Model',
25     fields: [
26         {name: 'id',      type: 'int'},
27         {name: 'user_id', type: 'int'},
28         {name: 'name',    type: 'string'}
29     ]
30 });
31
32 Ext.define('User', {
33     extend: 'Ext.data.Model',
34     fields: [
35         {name: 'id',   type: 'int'},
36         {name: 'name', type: 'string'}
37     ],
38     // we can use the hasMany shortcut on the model to create a hasMany association
39     hasMany: {model: 'Product', name: 'products'}
40 });
41 </pre></code>
42
43  * <p>Above we created Product and User models, and linked them by saying that a User hasMany Products. This gives
44  * us a new function on every User instance, in this case the function is called 'products' because that is the name
45  * we specified in the association configuration above.</p>
46  * 
47  * <p>This new function returns a specialized {@link Ext.data.Store Store} which is automatically filtered to load
48  * only Products for the given model instance:</p>
49  * 
50 <pre><code>
51 //first, we load up a User with id of 1
52 var user = Ext.create('User', {id: 1, name: 'Ed'});
53
54 //the user.products function was created automatically by the association and returns a {@link Ext.data.Store Store}
55 //the created store is automatically scoped to the set of Products for the User with id of 1
56 var products = user.products();
57
58 //we still have all of the usual Store functions, for example it's easy to add a Product for this User
59 products.add({
60     name: 'Another Product'
61 });
62
63 //saves the changes to the store - this automatically sets the new Product's user_id to 1 before saving
64 products.sync();
65 </code></pre>
66  * 
67  * <p>The new Store is only instantiated the first time you call products() to conserve memory and processing time,
68  * though calling products() a second time returns the same store instance.</p>
69  * 
70  * <p><u>Custom filtering</u></p>
71  * 
72  * <p>The Store is automatically furnished with a filter - by default this filter tells the store to only return
73  * records where the associated model's foreign key matches the owner model's primary key. For example, if a User
74  * with ID = 100 hasMany Products, the filter loads only Products with user_id == 100.</p>
75  * 
76  * <p>Sometimes we want to filter by another field - for example in the case of a Twitter search application we may
77  * have models for Search and Tweet:</p>
78  * 
79 <pre><code>
80 Ext.define('Search', {
81     extend: 'Ext.data.Model',
82     fields: [
83         'id', 'query'
84     ],
85
86     hasMany: {
87         model: 'Tweet',
88         name : 'tweets',
89         filterProperty: 'query'
90     }
91 });
92
93 Ext.define('Tweet', {
94     extend: 'Ext.data.Model',
95     fields: [
96         'id', 'text', 'from_user'
97     ]
98 });
99
100 //returns a Store filtered by the filterProperty
101 var store = new Search({query: 'Sencha Touch'}).tweets();
102 </code></pre>
103  * 
104  * <p>The tweets association above is filtered by the query property by setting the {@link #filterProperty}, and is
105  * equivalent to this:</p>
106  * 
107 <pre><code>
108 var store = Ext.create('Ext.data.Store', {
109     model: 'Tweet',
110     filters: [
111         {
112             property: 'query',
113             value   : 'Sencha Touch'
114         }
115     ]
116 });
117 </code></pre>
118  */
119 Ext.define('Ext.data.HasManyAssociation', {
120     extend: 'Ext.data.Association',
121     requires: ['Ext.util.Inflector'],
122
123     alias: 'association.hasmany',
124
125     /**
126      * @cfg {String} foreignKey The name of the foreign key on the associated model that links it to the owner
127      * model. Defaults to the lowercased name of the owner model plus "_id", e.g. an association with a where a
128      * model called Group hasMany Users would create 'group_id' as the foreign key. When the remote store is loaded,
129      * the store is automatically filtered so that only records with a matching foreign key are included in the 
130      * resulting child store. This can be overridden by specifying the {@link #filterProperty}.
131      * <pre><code>
132 Ext.define('Group', {
133     extend: 'Ext.data.Model',
134     fields: ['id', 'name'],
135     hasMany: 'User'
136 });
137
138 Ext.define('User', {
139     extend: 'Ext.data.Model',
140     fields: ['id', 'name', 'group_id'], // refers to the id of the group that this user belongs to
141     belongsTo: 'Group'
142 });
143      * </code></pre>
144      */
145     
146     /**
147      * @cfg {String} name The name of the function to create on the owner model to retrieve the child store.
148      * If not specified, the pluralized name of the child model is used.
149      * <pre><code>
150 // This will create a users() method on any Group model instance
151 Ext.define('Group', {
152     extend: 'Ext.data.Model',
153     fields: ['id', 'name'],
154     hasMany: 'User'
155 });
156 var group = new Group();
157 console.log(group.users());
158
159 // The method to retrieve the users will now be getUserList
160 Ext.define('Group', {
161     extend: 'Ext.data.Model',
162     fields: ['id', 'name'],
163     hasMany: {model: 'User', name: 'getUserList'}
164 });
165 var group = new Group();
166 console.log(group.getUserList());
167      * </code></pre>
168      */
169     
170     /**
171      * @cfg {Object} storeConfig Optional configuration object that will be passed to the generated Store. Defaults to 
172      * undefined.
173      */
174     
175     /**
176      * @cfg {String} filterProperty Optionally overrides the default filter that is set up on the associated Store. If
177      * this is not set, a filter is automatically created which filters the association based on the configured 
178      * {@link #foreignKey}. See intro docs for more details. Defaults to undefined
179      */
180     
181     /**
182      * @cfg {Boolean} autoLoad True to automatically load the related store from a remote source when instantiated.
183      * Defaults to <tt>false</tt>.
184      */
185     
186     /**
187      * @cfg {String} type The type configuration can be used when creating associations using a configuration object.
188      * Use 'hasMany' to create a HasManyAssocation
189      * <pre><code>
190 associations: [{
191     type: 'hasMany',
192     model: 'User'
193 }]
194      * </code></pre>
195      */
196     
197     constructor: function(config) {
198         var me = this,
199             ownerProto,
200             name;
201             
202         me.callParent(arguments);
203         
204         me.name = me.name || Ext.util.Inflector.pluralize(me.associatedName.toLowerCase());
205         
206         ownerProto = me.ownerModel.prototype;
207         name = me.name;
208         
209         Ext.applyIf(me, {
210             storeName : name + "Store",
211             foreignKey: me.ownerName.toLowerCase() + "_id"
212         });
213         
214         ownerProto[name] = me.createStore();
215     },
216     
217     /**
218      * @private
219      * Creates a function that returns an Ext.data.Store which is configured to load a set of data filtered
220      * by the owner model's primary key - e.g. in a hasMany association where Group hasMany Users, this function
221      * returns a Store configured to return the filtered set of a single Group's Users.
222      * @return {Function} The store-generating function
223      */
224     createStore: function() {
225         var that            = this,
226             associatedModel = that.associatedModel,
227             storeName       = that.storeName,
228             foreignKey      = that.foreignKey,
229             primaryKey      = that.primaryKey,
230             filterProperty  = that.filterProperty,
231             autoLoad        = that.autoLoad,
232             storeConfig     = that.storeConfig || {};
233         
234         return function() {
235             var me = this,
236                 config, filter,
237                 modelDefaults = {};
238                 
239             if (me[storeName] === undefined) {
240                 if (filterProperty) {
241                     filter = {
242                         property  : filterProperty,
243                         value     : me.get(filterProperty),
244                         exactMatch: true
245                     };
246                 } else {
247                     filter = {
248                         property  : foreignKey,
249                         value     : me.get(primaryKey),
250                         exactMatch: true
251                     };
252                 }
253                 
254                 modelDefaults[foreignKey] = me.get(primaryKey);
255                 
256                 config = Ext.apply({}, storeConfig, {
257                     model        : associatedModel,
258                     filters      : [filter],
259                     remoteFilter : false,
260                     modelDefaults: modelDefaults
261                 });
262                 
263                 me[storeName] = Ext.create('Ext.data.Store', config);
264                 if (autoLoad) {
265                     me[storeName].load();
266                 }
267             }
268             
269             return me[storeName];
270         };
271     },
272     
273     /**
274      * Read associated data
275      * @private
276      * @param {Ext.data.Model} record The record we're writing to
277      * @param {Ext.data.reader.Reader} reader The reader for the associated model
278      * @param {Object} associationData The raw associated data
279      */
280     read: function(record, reader, associationData){
281         var store = record[this.name](),
282             inverse;
283     
284         store.add(reader.read(associationData).records);
285     
286         //now that we've added the related records to the hasMany association, set the inverse belongsTo
287         //association on each of them if it exists
288         inverse = this.associatedModel.prototype.associations.findBy(function(assoc){
289             return assoc.type === 'belongsTo' && assoc.associatedName === record.$className;
290         });
291     
292         //if the inverse association was found, set it now on each record we've just created
293         if (inverse) {
294             store.data.each(function(associatedRecord){
295                 associatedRecord[inverse.instanceName] = record;
296             });
297         }
298     }
299 });