3 This file is part of Ext JS 4
5 Copyright (c) 2011 Sencha Inc
7 Contact: http://www.sencha.com/contact
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.
12 If you are unsure which license is appropriate for your use, please contact the sales department at http://www.sencha.com/contact.
17 * @class Ext.data.HasManyAssociation
18 * @extends Ext.data.Association
20 * <p>Represents a one-to-many relationship between two models. Usually created indirectly via a model definition:</p>
23 Ext.define('Product', {
24 extend: 'Ext.data.Model',
26 {name: 'id', type: 'int'},
27 {name: 'user_id', type: 'int'},
28 {name: 'name', type: 'string'}
33 extend: 'Ext.data.Model',
35 {name: 'id', type: 'int'},
36 {name: 'name', type: 'string'}
38 // we can use the hasMany shortcut on the model to create a hasMany association
39 hasMany: {model: 'Product', name: 'products'}
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>
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>
51 //first, we load up a User with id of 1
52 var user = Ext.create('User', {id: 1, name: 'Ed'});
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();
58 //we still have all of the usual Store functions, for example it's easy to add a Product for this User
60 name: 'Another Product'
63 //saves the changes to the store - this automatically sets the new Product's user_id to 1 before saving
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>
70 * <p><u>Custom filtering</u></p>
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>
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>
80 Ext.define('Search', {
81 extend: 'Ext.data.Model',
89 filterProperty: 'query'
94 extend: 'Ext.data.Model',
96 'id', 'text', 'from_user'
100 //returns a Store filtered by the filterProperty
101 var store = new Search({query: 'Sencha Touch'}).tweets();
104 * <p>The tweets association above is filtered by the query property by setting the {@link #filterProperty}, and is
105 * equivalent to this:</p>
108 var store = Ext.create('Ext.data.Store', {
113 value : 'Sencha Touch'
119 Ext.define('Ext.data.HasManyAssociation', {
120 extend: 'Ext.data.Association',
121 requires: ['Ext.util.Inflector'],
123 alias: 'association.hasmany',
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}.
132 Ext.define('Group', {
133 extend: 'Ext.data.Model',
134 fields: ['id', 'name'],
139 extend: 'Ext.data.Model',
140 fields: ['id', 'name', 'group_id'], // refers to the id of the group that this user belongs to
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.
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'],
156 var group = new Group();
157 console.log(group.users());
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'}
165 var group = new Group();
166 console.log(group.getUserList());
171 * @cfg {Object} storeConfig Optional configuration object that will be passed to the generated Store. Defaults to
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
182 * @cfg {Boolean} autoLoad True to automatically load the related store from a remote source when instantiated.
183 * Defaults to <tt>false</tt>.
187 * @cfg {String} type The type configuration can be used when creating associations using a configuration object.
188 * Use 'hasMany' to create a HasManyAssocation
197 constructor: function(config) {
202 me.callParent(arguments);
204 me.name = me.name || Ext.util.Inflector.pluralize(me.associatedName.toLowerCase());
206 ownerProto = me.ownerModel.prototype;
210 storeName : name + "Store",
211 foreignKey: me.ownerName.toLowerCase() + "_id"
214 ownerProto[name] = me.createStore();
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
224 createStore: function() {
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 || {};
239 if (me[storeName] === undefined) {
240 if (filterProperty) {
242 property : filterProperty,
243 value : me.get(filterProperty),
248 property : foreignKey,
249 value : me.get(primaryKey),
254 modelDefaults[foreignKey] = me.get(primaryKey);
256 config = Ext.apply({}, storeConfig, {
257 model : associatedModel,
259 remoteFilter : false,
260 modelDefaults: modelDefaults
263 me[storeName] = Ext.create('Ext.data.Store', config);
265 me[storeName].load();
269 return me[storeName];
274 * Read associated data
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
280 read: function(record, reader, associationData){
281 var store = record[this.name](),
284 store.add(reader.read(associationData).records);
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;
292 //if the inverse association was found, set it now on each record we've just created
294 store.data.each(function(associatedRecord){
295 associatedRecord[inverse.instanceName] = record;