Extjs hasOne association not loading preoperly - extjs

I have a Person model which has an Address associated to it via 'hasOne'. Both models load data via REST proxy. If I load a person and try to get the address I can see a http request to the url of the addresses but without any kind of person id in it so my server sends an error.
Person:
Ext.define('AP.model.Person', {
extend: 'Ext.data.Model',
fields: [
{ name: 'id', type: 'int', persist : false },
{ name: 'name', type: 'string' }
],
proxy: {
type: 'rest',
url : AP_ROOT_URL + 'persons/'
},
associations: [{
type: 'hasOne',
model: 'AP.model.Addresses',
foreignKey: 'person_id',
primaryKey: 'id',
getterName: "getAddress"
}]
});
Address:
Ext.define('AP.model.Address', {
extend: 'Ext.data.Model',
fields: [
{ name: 'person_id', type: 'int', persist : false },
{ name: 'address', type: 'string' }
],
proxy: {
type: 'rest',
url : AP_ROOT_URL + 'addresses/'
}
});
The following code:
person.getAddress(function(address){
console.log(address);
});
creates a request to:
http://localhost/addresses
when it should create a request to:
http://localhost/addresses/person_id (http://localhost/addresses/1)

What you have here is a HasMany relation, not HasOne. You won't get HasOne to work with these models because, as said in the docs: "the owner model is expected to have a foreign key which references the primary key of the associated model". In your case, the foreign key is in the associated model (which makes it a 1-n relationship).

Related

Define mapping in reader

I have defined a custom ComboBox component, that I want to re-use with multiple Stores. It has a simple config as below.
Ext.define('Myapp.CustomCombo', {
extend: 'Ext.form.ComboBox',
valueField: 'id',
displayField: 'name'
});
The model is
Ext.define('Myapp.model.ComboModel',{
extend: 'Ext.data.Model',
fields: [
{ name: 'id', type: 'int' },
{ name: 'name', type: 'string' },
{ name: 'linkCls', type: 'string' }
]
});
I define multiple stores each with its own proxy config & identified by a unique storeId, as below
Ext.create('Myapp.store.EmployeeComboStore', {
model: 'Myapp.model.ComboModel',
storeId: 'employeeLOVComboStore',
proxy: {
type: 'rest',
url: '/employees/getLovData',
reader: {
type: 'json',
rootProperty: 'data'
}
}
});
The server responds with a json as below
{
"data" : [
{"employeeId": 1, "employeeName": "Chris"},
{"employeeId": 2, "employeeName": "Jack"},
]
}
I can have multiple such stores, like departmentStore with a different proxy URL and where in, the server response could be
{
"data" : [
{"departmentId": 1, "departmentName": "Sales"},
{"departmentId": 2, "departmentName": "Marketing"},
]
}
I want to define a mapping in the Reader, with instructions to map data differently in different stores, as in.. employeeId should be mapped to 'id' & employeeName to 'name' in employeeStore, whereas departmentId should be mapped to 'id' & departmentName to 'name' in departmentStore.
I've seen that there are options to define mapping for each field in a Model, but I would want to define a mapping in a Reader, since the server responds with data from a relational database where field names would be the columnNames.
What you can do, is to send along metaData from the server to the client.
The json response can look like this:
{
data: [{ ... }],
msg: "...",
total: 99,
metaData: {
fields: [{ ... }],
columns: [{ ... }],
idProperty: "id",
messageProperty: "msg",
root: "data"
}
}
In you case it would be sufficient if the json response would look like this
{
data: [{ ... }],
metaData: {
fields: [
{ name: 'Id', type: 'int', mapping: 'departmentId' },
{ name: 'Name', type: 'string', mapping: 'departmentName' },
]
}
}
Here is also a good example how it works: Basic Meta Data Config

ExtJS load data to Form from Store with association

I have a single form that has fields for a Employee Model and fields for Person Model.
Employee Model
Ext.define('App.model.Employee', {
extend: 'Ext.data.Model',
fields: [{
name: 'EmployeeId',
type: 'int'
},
{
name: 'PersonId',
type: 'int'
},
'EmployeeNumber',
'JoinDate'
],
belongsTo: 'App.model.Person'
});
Person Model
Ext.define('App.mode.Person', {
extend: 'Ext.data.Model',
fields: [{
name: 'PersonId',
type: 'int'
},
'FirstName',
'LastName'
],
hasMany: {
model: 'App.model.Employee',
name: 'Employees'
}
});
My Store:
var store = Ext.create('Ext.data.Store', {
model: 'App.model.Employee',
autoLoad: false,
autoSync: true,
proxy: {
type: 'ajax',
api: {
read: 'api/employee/getemployee'
},
reader: {
type: 'json',
successProperty: 'success',
root: 'data',
messageProperty: 'message'
}
}
});
This is my actual JSON
"data": [{
"EmployeeId": 5,
"PersonId": 1,
"EmployeeNumber": 2001,
"JoinDate" : "",
"Person": {
"PersonId": 1,
"FathersLast": "SMITH",
"FirstName": "JOHN"
}
}],
My question is how does my json response (from server) should be structured in order to load store successful?
You can find explanation and sample code in Ext data package guide section "Loading Nested Data". Other example is in the heading of Association documentation. Both with sample JSON files showing the required structure.
After looking at your code and json structure i can recognize that each employee has a person object, so you need to correct your mapping. Instead of Defining hasMany relationship in person model, you should define hasOne relationship for person in employee.
hasOne: {
model: 'App.mode.Person',
name: 'Person'
}
Please try this out. Your json structure looks good.

Declaring model with belongsTo not generating getter

Based on some examples of Ext.data.Model with associations I wrote the following class:
Ext.define('MyApp.model.Children',{
extend: 'Ext.data.Model',
fields : [{
name: 'parent' //object of the belongsTo
},{
name: 'description',
type: 'string'
}],
belongsTo : [{
name: 'parent',
foreignKey: 'parent', //also tried parent.id
instanceName: 'parent',
getterName: 'getParent',
model: 'MyApp.model.Parent'
}],
proxy : {
type: 'rest',
url: '../rest/children',
reader : {
type: 'json',
root: 'data'
}
}
});
Shouldn't this definition generate a getChildren method? The MyApp.model.Parent also have a proxy defined.
I'm testing with:
var store = Ext.create('Ext.data.Store',{
model: 'MyApp.model.Children'
});
store.load(function(recs){
console.log(recs[0].getParent); //prints undefined instead of function
});
It looks like your parent model isn't loaded. Try adding the requires configuration to your child model.
Ext.define('MyApp.model.Children', {
extend: 'Ext.data.Model',
//ensures the Parent model is loaded first
requires: 'MyApp.model.Parent',
fields: ...

EXTJS4--Why don't my associated stores load child data?

So I have a parent and child store, illustrated here:
Parent Model
Ext.define('APP.model.Client', {
extend: 'Ext.data.Model',
requires: [
'APP.model.Website', 'Ext.data.association.HasMany', 'Ext.data.association.BelongsTo'],
fields: [{
name: 'id',
type: 'string'
}, {
name: 'name',
type: 'string'
}, {
name: 'slug',
type: 'string'
}, {
name: 'active',
type: 'boolean'
}, {
name: 'current',
type: 'boolean'
}],
hasMany: {
model: 'APP.model.Website',
name: 'websites'
}
});
Child Model
Ext.define('APP.model.Website', {
extend: 'Ext.data.Model',
fields: [{
name: 'id',
type: 'string'
}, {
name: 'client_id',
type: 'string'
}, {
name: 'sub_domain',
type: 'string'
}, {
name: 'active',
type: 'boolean'
}],
belongsTo: 'APP.model.Client'
});
Using an AJAX call via the server, I am loading the Clients store, and that is loading fine. But the Websites store isn't populated, and when I breakpoint on the Clients store on.load function, to see what it's populated with, the Client store is only populated with the client data, but in the raw property for that store, I can see all the websites data. So it's being returned correctly, but my extjs isn't correct. Here are the stores:
Client Store
Ext.define('APP.store.Clients', {
extend: 'Ext.data.Store',
autoLoad: false,
model: 'APP.model.Client',
proxy: {
type: 'ajax',
url: '/client/list',
reader: {
type: 'json',
root: 'items'
}
},
sorters: [{
property: 'name',
direction: 'ASC'
}]
});
Websites Store
Ext.define('APP.store.Websites', {
extend: 'Ext.data.Store',
requires: ['Ext.ux.Msg'],
autoLoad: false,
model: 'APP.model.Website',
proxy: {
type: 'ajax',
url: '/client/list',
reader: {
type: 'json',
root: 'items'
},
writer: {
type: 'json'
}
},
sorters: [{
property: 'sub_domain',
direction: 'ASC'
}]
});
My final result is...I would like to populate both stores so I can click on an element, and when it loads something from the parent store, I can access the child store(s) (there will be more when I figure out this problem) to populate a couple grid(s) in tabs.
What am I missing as far as my setup? I just downloaded extjs4 a couple days ago, so I am on 4.1.
Put your proxies in your models, unless you have a good reason not to [1]
Make sure you require the related model(s), either in the same file, or earlier in the application
Use foreignKey if you want to load the related data at will (i.e. with a later network request).
Use associationKey if the related data is loaded in the same (nested) response
Or just use both
Always name your relationships (otherwise the name will be weird if using namespaces).
Always use the fully qualified model name for the model property in your relationships
Working code:
model/Contact.js:
Ext.define('Assoc.model.Contact', {
extend:'Ext.data.Model',
requires:[
'Assoc.model.PhoneNumber'
],
fields:[
'name' /* automatically has an 'id' field */
],
hasMany:[
{
model:'Assoc.model.PhoneNumber', /*use the fully-qualified name here*/
name:'phoneNumbers',
foreignKey:'contact_id',
associationKey:'phoneNumbers'
}
],
proxy:{
type:'ajax',
url:'assoc/data/contacts.json',
reader:{
type:'json',
root:'data'
}
}
});
model/PhoneNumber.js:
Ext.define('Assoc.model.PhoneNumber', {
extend:'Ext.data.Model',
fields:[
'number',
'contact_id'
],
proxy:{
type:'ajax',
url:'assoc/data/phone-numbers.json',
reader:{
type:'json',
root:'data'
}
}
});
data/contacts.json:
{
"data":[
{
"id":1,
"name":"neil",
"phoneNumbers":[
{
"id":999,
"contact_id":1,
"number":"9005551234"
}
]
}
]
}
data/phone-numbers.json
{
"data":[
{
"id":7,
"contact_id":1,
"number":"6045551212"
},
{
"id":88,
"contact_id":1,
"number":"8009996541"
},
]
}
app.js:
Ext.Loader.setConfig({
enabled:true
});
Ext.application({
requires:[
'Assoc.model.Contact'
],
name:'Assoc',
appFolder:'Assoc',
launch:function(){
/* load child models that are in the response (uses associationKey): */
Assoc.model.Contact.load(1, {
success: function(record){
console.log(record.phoneNumbers());
}
});
/* load child models at will (uses foreignKey). this overwrites child model that are in the first load response */
Assoc.model.Contact.load(1, {
success: function(record){
record.phoneNumbers().load({
callback:function(){
console.log(arguments);
}
});
}
});
}
});
[1] A store will use its model's proxy. You can always override the store's proxy if need be. You won't be able to use Model.load() if the model has no proxy.
Your assumption is wrong. You expect that the WebSite store loads itself but that is not how it works. What you can do is the following (this is untested but is how I do it in all my projects):
In your clients grid add a listener for the itemclick event to call the following method (showWebSites). It will receive the selected client record containing the selected APP.model.Client instance. Then, and given that each client has a set of WebSites, the method will load the APP.store.Websites store and the client´s websites will be displayed in your view.
showWebSites: function (sender, selectedClient) {
Ext.StoreManager.lookup('APP.store.Websites')
.loadData(selectedClient.data.WebSites);
}
This is the way. I hope you find it useful.

Sencha touch 2.0 many-to-many associations - how?

I've been having a hell of a time getting Sencha Touch 2.0 hasMany associations working, especially since it looks like their data models don't directly allow for many-to-many relationships. I've got two models - People and Roles (theere are a bunch more, but these are the two that matter in this example) , each has a many-to-many to the other.
I originally thought that I could do this with a hasMany in each of the models, but snce the data is stored in third-normal form in my db, I figure that I need a third, person-to-role model. Code is here:
Ext.define('SMToolkit.model.Person', {
extend: 'Ext.data.Model',
config: {
fields: [
'id',
'first_name',
'last_name',
'email',
'address',
'phone1',
'phone2',
'type',
'location'
],
hasMany: [
{
model: 'SMToolkit.model.Person_Role',
name: 'role'
}
],
proxy: {
type: 'rest',
url : 'index.php/api/persons'
}
}
});
Ext.define('SMToolkit.model.Role', {
extend: 'Ext.data.Model',
config: {
fields: [
'id',
'name',
'description',
'type',
'show_id'
],
hasMany: [
{
model: 'SMToolkit.model.Person_Role',
name: 'person'
},
{
model: 'SMToolkit.model.Scene_Role',
name: 'scene'
},
{
model: 'SMToolkit.model.Thing',
name: 'thing'
}
],
proxy: {
type: 'rest',
url : 'index.php/api/roles'
}
}
});
Ext.define('SMToolkit.model.Person_Role', {
extend: 'Ext.data.Model',
config: {
fields: [
'person_id',
'role_id'
],
associations: [
{
type: 'belongsTo',
model: 'SMToolkit.model.Person',
name: 'person'
},
{
type: 'belongsTo',
model: 'SMToolkit.model.Role',
name: 'role'
},
],
proxy: {
type: 'rest',
url : 'index.php/api/personsroles'
}
}
});
I've confirmed that the personsroles url above does in fact return a valid data set, so I know that there should be something in there...
When I look at a Role record, I can see fields for the associated stores, but even if I know for certain that there's an appropriate record in the Person_Role table in the db, the Persons array in the record is empty.
I'm getting the record like so:
onRoleSelect: function(list, index, node, record) {
var editButton = this.getEditButton();
if (!this.showRole) {
this.showRole = Ext.create('SMToolkit.view.role.Show');
}
person = record.person();
thing = record.thing();
scene = record.scene();
person.load();
thing.load();
scene.load();
// Bind the record onto the view
this.showRole.setRecord(record);
// Push the show show view into the navigation view
this.getRoleContainer().push(this.showRole);
},
What am I doing wrong? Why is there no association data?
Here's an alternative approach for handling complex model relations in Sencha.
I've not yet tested it but I think it will likely handle Many-Many relations as well.
Recursive M-M relations might cause you grief with the linkChildAssociations() function.
http://appointsolutions.com/2012/07/using-model-associations-in-sencha-touch-2-and-ext-js-4/

Resources