Todo sobre la manzana y más

Sencha Touch 2 Models – hasMany Associations, PHP Example

In this article you will learn how to use the hasMany association, a feature of Sencha Touch models that allows you to connect two models in a one-to-many relationship. The model configs you will learn about in this post are the following:

Using Google Chrome, you can browse to the index.html file, open the developer tools and inspect the request to the rooms.php file. The console’s output should look similar to this:

The query string parameters clearly show a filter property that contains the id of the hotel the rooms belong to. This is one of the behaviors that the hasMany association provides for us.

How It Works

As you can see in the code, you can obtain the rooms associated with a hotel by invoking the rooms() method of the Hotel model, which returns an instance of a data store. The method is automatically created based on the hasMany config:

1

hasMany: {

2

model: 'App.model.Room',

3

name:'rooms'

4

}

In the app.js file, you will now add a couple of rooms to the current hotel:

The call to rooms.sync() will upload the rooms to the server. Chrome’s console should reflect the operation:

The hotelId field of these rooms is set to 1, which is the id of their parent hotel. Note that you did not have to take care of this. It happens automatically thanks to the hasMany association you defined.