Backbone relational, keep foreign key ids when using relations in models - backbone.js

i have working example of code with relations, but there is a lack - backbone replaces my foreign id with related model, i would like to keep as foreign id and to add related model with new key.. is it possible?
In the following example engineId will be replaces with related model. Is it possible to keep as engineId as related model with key 'engine'?
window.Car = Backbone.RelationalModel.extend({
defaults : {
id : null,
brand : null,
engineId : null,
}
});
window.Engine = Backbone.RelationalModel.extend({
defaults : {
id : null,
type : null,
},
relations: [{
type : 'HasMany',
key : 'cars',
relatedModel : 'Car',
reverseRelation: {
key: 'engineId',
}
}]
});
var engines = new Backbone.Collection([
{id : 1, type : 'electric'},
{id : 2, type : 'diesel'},
], {model: window.Engine});
var cars = new Backbone.Collection([
{id : 1, brand : 'Toyota', engineId : 2},
{id : 2, brand : 'Ford', engineId : 2},
{id : 3, brand : 'Tesla', engineId : 1},
], {model: window.Car});
cars.each(function(car){
console.log(car.get('id'), car.get('brand'), car.get('engineId').get('type'));
});

Is there any reason you can't just get the id from the Engine model? Eg.
car.engine.get('id')

Related

Displaying Nested Json as individual columns on the UI Grid

My rest call gives me an array of nested objects which differs for every outer object...
Example:
$scope.data = [
{
id :5,
nested : [
{name : 'SHOE', value : 'ABC'},
{name : 'TIE', value : 'DEF'}
]
},
{
id :6,
nested : [
{name : 'SHIRT', value : 'XYZ'},
{name : 'TIE', value : 'GHI'}
]
},
{
id :8,
nested : [
{name : 'CAP', value : 'FD1'},
{name : 'fixed', value : 'Domain1'}
]
}
];
But I want it to be displayed on the grid columns as
ID | SHOE| TIE| SHIRT| CAP | fixed
how should I achieve this?
There are 2 solutions using cellTemplate and calling a function from 'field' I am able to achieve this but there are just to many iterations and I dont want that...
Also I read about Expandalable Grids, which again does not suficy this..
Plz reply... I'm not sure if this feature exists or not...
This is how I have done but i need a better solution...
`
$scope.columnDefsService = ['fixed', 'SHOE', 'CAP', 'TIE', 'SHIRT', 'JEANS'];
$scope.gridOptions = {
enableSorting: true,
columnDefs: [
{ name:'id', width : '50' }
],
data : $scope.data
};
_.each($scope.columnDefsService, function(col, index){
var temp = $scope.columnDefsService[index];
$scope.gridOptions.columnDefs.push(
{name : $scope.columnDefsService[index], field: 'nested[0]', cellTemplate: '<div>{{grid.appScope.fun(col,row.entity.nested)}}<div>'}
)
});
$scope.fun = function(col, attributes){
var temp = '';
_.each(attributes, function(attribute){
if(attribute.name === col.name){
console.log('true');
temp = attribute.value
}
})
return temp;
};
}]);
`
You can use cellTemplate property in $scope.gridOptions .For this you can refer to the example below.
$scope.gridOptions = {
enableSorting: true,
columnDefs: [
{ name:'id', width : '50', cellTemplate : '<button ng-repeat="record in row.entity.nested ">{{record.name }}</button>' }
]};

Is it possible to have multiple hasMany relationships using the same model?

I have a situation where I have a model meant to store several lists of chemicals. The chemical model is the same for each of the hasMany relationships.
I need something like this:
Ext.define('HandSurvey.model.ChemicalRisks', {
extend: 'Ext.data.Model',
requires: ['Ext.data.identifier.Uuid'],
config: {
idProperty: 'id',
identifier: 'uuid',
fields: [
{ name: 'id', type: 'auto' }
],
associations: [
{
type: 'hasMany',
model : 'HandSurvey.model.SpecificChemical',
name : 'fiberglassResins',
store : {
type: 'sql'
}
},
{
type: 'hasMany',
model : 'HandSurvey.model.SpecificChemical',
name : 'paintsStains',
store : {
type: 'sql'
}
},
],
proxy: {
type: 'sql'
}
}
});
But this would cause each list to bind to every SpecificChemical that belongs to the ChemicalRisks model, not just the ones meant to belong to that hasMany. It seems as though I would need to join on multiple fields
Is it possible to do this? Or do I have to make a bunch of the exact same models/stores with different names?
sure you can!
use associationKey and the autogenerated stores of the associations
associations: [
{
type: 'hasMany',
model : 'HandSurvey.model.SpecificChemical',
name : 'fiberglassResins',
associationKey : 'fiberglassResins'
},
{
type: 'hasMany',
model : 'HandSurvey.model.SpecificChemical',
name : 'paintsStains',
associationKey : 'paintsStains'
},
]
Given a response like this: {
"response" : {
"fiberglassResins": [
{
"id" : 1
"name" : "Polyester"
},
{
"id" : 2
"name" : "E-Glass"
}
],
"paintsStains": [
{
"id" : 1
"name" : "item1"
},
{
"id" : 2
"name" : "item2"
}
]
}
}
Then you bind your main model to a store lets say ItemsStore.
IMPORTANT each record of ItemsStore will get autogenerated by Sencha: fiberglassResinsStore and paintsStainsStore.
Yo can console.log() each record to see the actual stores.

Sencha touch 2.2 sql proxy not inserting data

I successfully tried sencha touch app example showed here
They are using store proxy type as localstorage, its working good and then i changed the proxy type to sql as shown below
Ext.define('notesApp.store.Notes', {
extend : 'Ext.data.Store',
requires : 'Ext.data.proxy.Sql',
config : {
model : 'notesApp.model.Note',
proxy : {
type : 'sql',
database: "SqlProxyTest",
table: "Notes",
id : 'notes-app-store'
},
sorters : [{property : 'dateCreated', direction : 'DESC'}],
grouper : {
sortProperty : 'dateCreated',
direction : 'DESC',
groupFn : function(record) {
if(record && record.data.dateCreated) {
return record.data.dateCreated.toString();
}
return '';
}
}
}
});
There is no error.
I can insert data and i can see the record in list view, but chrome resource showing "The Node table is empty".
If i refresh the browser the record is gone from the list.
Am i missing anything or is it right way to use sql proxy in sencha touch ?
If you have change your model (add a field) you have to drop the table and recreate it.
And when you add a new row on your datastore be sure to put all fields.
Example if i have a model with firstName, lastName, email :
// This one is not added cause email is absent
Ext.getStore('Users').add([{
firstName: 'Toto',
lastName: 'test',
}]);
// This one is added
Ext.getStore('Users').add([{
firstName: 'toto',
lastName: 'test',
email : 'toto#test.te'
}]);
The mistake i did was, i created id for the record i am trying to insert as they showed in that demo example, when i changed below model from
Ext.define("NotesApp.model.Note", {
extend: "Ext.data.Model",
config: {
idProperty: 'id',
fields: [
{ name: 'id', type: 'int' },
{ name: 'dateCreated', type: 'date', dateFormat: 'c' },
{ name: 'title', type: 'string' },
{ name: 'narrative', type: 'string' }
]
}
});
to
Ext.define('notesApp.model.Note', {
extend : 'Ext.data.Model',
config : {
fields : [
{ name : 'dateCreated', type : 'string', dateFormat : 'D'},
{ name : 'title', type : 'string'},
{ name : 'narrative', type : 'string'}
],
validations : [
{type : 'presence', field : 'dateCreated'},
{type : 'presence', field : 'title', message : 'Please enter a title for the note!'}
]
}
});
Everything works fine.

Backbone-relational not setting parent model, or reverse relation _id

In this app, an incident is something that happened, and a feeling is a nested object that describes how you felt about it. Here's my Incident model:
window.Incident = Backbone.RelationalModel.extend({
urlRoot: "/incidents",
idAttribute: "_id",
relations:[{
type: Backbone.HasMany,
key: 'feelings',
relatedModel: 'Feeling',
reverseRelation: {
key: 'incident',
includeInJSON: '_id'
}
},
{
type: Backbone.HasMany,
key: 'thoughts',
relatedModel: 'window.Thought',
reverseRelation: {
key: 'incident',
includeInJSON: '_id'
}
}],
// rest of model...
});
And here is the Feeling model:
window.Feeling = Backbone.RelationalModel.extend({
urlRoot: '/incidents',
idAttribute: '_id'
});
At this point, I can CRUD incidents, and also feelings. But, feelings are not being assigned the reverse relation. In a feeling, the attribute 'incident' is given the value 'null'. In my MongoDB collection, I get these two unrelated objects:
{ "description" : "I feel sad", "_id" : ObjectId("50d3b1462ff17f07cf000002") }
{ "name" : "asdf", "intensityBefore" : "asdf", "intensityAfter" : "asdf", "incident" : null, "_id" : ObjectId("50d3b14e2ff17f07cf000003") }
I have the full project up at https://github.com/mhurwi/cbt-app/tree/relational.
Note, this app is built off a starter app by Christophe Coenraets: https://github.com/ccoenraets/nodecellar
It's been many hours now, and I cannot understand why the relationship is not being set by backbone-relational.
You may need to declare BackboneRelational.HasOne on the Feelings model, like so:
window.Feeling = Backbone.RelationalModel.extend({
urlRoot: '/incidents',
idAttribute: '_id',
relations:[{
type: Backbone.HasOne,
key: 'incident',
relatedModel: 'Incident'
}]
});

Ext has many association store does not load

I have two models defined, ScoreCard and CaregoryWeight. A ScoreCard has many CategoryWeights.
When I create a grid and pass the association store to it (scoreCard.categoryWeights()), it displays nothing even though items are returned from the RESTful service.
What is wrong? please help.
Below is my code:
Ext.define(ModelNames.CategoryWeight, {
extend : 'Ext.data.Model',
idProperty : 'id',
fields : [ {
name : 'id',
type : 'int'
}, {
name : 'weight',
type : 'float'
}, {
name : 'category_id',
type : 'int'
}, {
name : 'scorecard_id',
type : 'int'
} ],
associations : [ {
type : 'belongsTo',
model : ModelNames.Category,
primaryKey : 'id',
forgientKey : 'category_id'
}, {
type : 'belongsTo',
model : ModelNames.ScoreCard,
primaryKey : 'id',
forgientKey : 'scorecard_id'
} ]});
Ext.define(ModelNames.ScoreCard, {
extend : 'Ext.data.Model',
idProperty : 'id',
fields : [ {
name : 'id',
type : 'int'
}, {
name : 'description',
type : 'string',
defaults : ''
}, {
name : 'isTemplate',
type : 'boolean',
defaults : true
}, {
name : 'isValid',
type : 'boolean',
defaults : false
} ],
associations : [ {
type : 'hasMany',
model : ModelNames.ScoreRecord,
name : 'scoreRecords',
storeConfig : {
autoLoad : true,
autoSync : true,
proxy : {
type : 'rest',
url : '/' + CONTEXT_PATH + '/RESTFul/ScoreRecord',
reader : {
type : 'json',
root : 'items'
},
writer : 'json'
}
}
}, {
type : 'hasMany',
model : ModelNames.CategoryWeight,
name : 'categoryWeights',
storeConfig : {
autoLoad : true,
autoSync : false,
proxy : {
type : 'rest',
url : '/' + CONTEXT_PATH + '/RESTFul/CategoryWeight',
reader : {
type : 'json',
root : 'items'
},
writer : 'json'
}
}
} ]});
Typo: foreignKey
Since answers are not allowed to be less than two words, I'll add that apart from spotting the typo, I have no idea if your code will work, why or why not.

Resources