Represents a one-to-many relationship between two models. Usually created indirectly via a model definition:
Ext.regModel('Product', {
fields: [
{name: 'id', type: 'int'},
{name: 'user_id', type: 'int'},
{name: 'name', type: 'string'}
]
});
Ext.regModel('User', {
fields: [
{name: 'id', type: 'int'},
{name: 'name', type: 'string'}
],
hasMany: {model: 'Product', name: 'products'}
});
Above we created Product and User models, and linked them by saying that a User hasMany Products. This gives us a new function on every User instance, in this case the function is called 'products' because that is the name we specified in the association configuration above.
This new function returns a specialized Store which is automatically filtered to load only Products for the given model instance:
//first, we load up a User with id of 1
var user = Ext.ModelMgr.create({id: 1, name: 'Ed'}, 'User');
//the user.products function was created automatically by the association and returns a Store
//the created store is automatically scoped to the set of Products for the User with id of 1
var products = user.products();
//we still have all of the usual Store functions, for example it's easy to add a Product for this User
products.add({
name: 'Another Product'
});
//saves the changes to the store - this automatically sets the new Product's user_id to 1 before saving
products.sync();
The new Store is only instantiated the first time you call products() to conserve memory and processing time, though calling products() a second time returns the same store instance.
Custom filtering
The Store is automatically furnished with a filter - by default this filter tells the store to only return records where the associated model's foreign key matches the owner model's primary key. For example, if a User with ID = 100 hasMany Products, the filter loads only Products with user_id == 100.
Sometimes we want to filter by another field - for example in the case of a Twitter search application we may have models for Search and Tweet:
var Search = Ext.regModel('Search', {
fields: [
'id', 'query'
],
hasMany: {
model: 'Tweet',
name : 'tweets',
filterProperty: 'query'
}
});
Ext.regModel('Tweet', {
fields: [
'id', 'text', 'from_user'
]
});
//returns a Store filtered by the filterProperty
var store = new Search({query: 'Sencha Touch'}).tweets();
The tweets association above is filtered by the query property by setting the filterProperty, and is equivalent to this:
var store = new Ext.data.Store({
model: 'Tweet',
filters: [
{
property: 'query',
value : 'Sencha Touch'
}
]
});