Extjs hasOne association local mode - extjs

I try to implement hasOne association in ExtJs 4. I use associationKey to load related model.
For example I have Person model. Some people may have spouse, so server side response with nested data like:
...
spouse: {
id: 5,
name: ...
...
}
Now when I use gettername function like:
var spouse = person.getSpouse()
If person has nested data like in example above it will return Person model object that is spouse of first one. But if there was no nested data, ExtJs try to load it dynamicly requesting the server. I want prevent this requests, can you help me?

Ok, so I thing I solve this myself. The reason is ExtJs tryed to load nested hasOne related data is because server sended
{
...
spouse_id: null,
spouse: null,
...
}
instead of:
{
...
spouse_id: null,
spouse: {},
...
}

Related

How does one get properties from related table as properties of it's own table in Laravel 5?

The question might sound a little bit confusing but I don't know how to explain it better in one sentence.
This describes basically what the problem is:
I have a Users table which can contain 2 types of users. I know how I can separate by role. But here's the thing, users with role 1(editor_in_chief) have different attributes than users with role 2(reviewer).
My idea was to create a table named 'reviewer_attributes' and 'editor_in_chief_attributes' and create a one-to-one relation with this table to hold the attributes for the users table.
Maybe you have a better idea, that would be great as well. But for this scenario, I would like to know if it is possible to make a call to the database and to get these users' properties from the other table as properties of the User object.
When using a DB call using relations laravel will give me something like this:
user {
id: 1,
name: "Name",
reviewer_attributes: {
attribute_1: 'attribute_1',
attribute_2: 'attribute_2',
attribute_3: 'attribute_3',
}
}
But this is what I want to object to obtain look like:
user {
id: 1,
name: "Name",
attribute_1: 'attribute_1',
attribute_2: 'attribute_2',
attribute_3: 'attribute_3',
}
I want to achieve this by a single database call instead of setting the properties after the call.
I find this a very interesting topic, I hope you could help!
If I got your problem right, you may call somthing like this:
DB::table('users')
->join('reviewer_attributes', 'users.id', '=', 'reviewer_attributes.user_id')
->find($id);
you may add select to get specific attributes of each table:
DB::table('users')
->join('reviewer_attributes', 'users.id', '=', 'reviewer_attributes.user_id')
->select('users.id', 'users.name', 'reviewer_attributes.*')
->find($id);
Update: You can also use collections to restructure your results returned by Eloquent:
$result = User::with('reviewerAttributes')->find($id);
$result = $result->get('reviewer_attributes')
->merge($result->forget('reviewer_attributes')->all())
->all();
You need export model to Json?
If so, override toArray method
public function toArray()
{
$arr = parent::toArray();
$reviewer_attributes = $this->getReviewerAttributesSomeHow();
return array_merge($arr, $reviewer_attributes);
}

How to fetch nested relations on Kinvey

So I'm working in an AngularJs app that is connected to a Kinvey backend. www.kinvey.com
In Kinvey we can fetch an entity and it's relations like this:
var promise = $kinvey.DataStore.get('events', 'event-id', {
relations : { location: 'locations' }
});
http://devcenter.kinvey.com/angular/guides/datastore#JoiningOperators
Relational Data / Fetching
The above is actually getting an event entity from the events collection and it's also fetching the data of the locations associated to it (which are in a different collection), so far so good we are able to retrieve an entity and it's associated entities ...
Now how could I retrieve the associations of those locations ?
In other words how can I retrieve nested associations ?
Thanks.
Like this:
$kinvey.DataStore.find('collection1', null, {
relations: {
name: "collection2",
"name.name": "collection3"
}
});
https://support.kinvey.com/discussion/201272198/nested-relations

Backbone View Design

I'm trying to create a html page like this
Publisher (Master) - Use CompositeView
Book List (Detail) - User ItemView
Video List (Detail) - ????? 1. What to use for this detail ?????
Should I get all the data at once request or separate into 3 requests?
ABC Publisher
Book1, Book2, Book3...
Video1, Video2, Video3...
Your question pretty broad, but lets to clarify.
1) Shorty about view:
Publisher - CompositeView? It will be correct approach if you are going to render in this view PublisherModel or PublisherCollection. If this view just a wrap for child views, use LayoutView.
Book List - looks like you are going to render collection here, so you should use CollectionView or CompositeView instead ItemView. ItemView should be used in case you would like to render single model.
2) Common approach use separate request for each collection or model. In your case you should send request for video, another for books and so on. If you would like to get all data in one request u'd better to create something like Controller - it will be in charge to parse this request response and provide parsed data to special collections.
This seems like a great use case for backbone-relational. In your server side code you define your json to contain nested elements. So each publisher would have a book list and a video list that's returned in the json. Then backbone-relational will auto-parse those and create collections/models for you. So you could say publisher.get('books') and you'd get your books collection. You also can get a reference from your books in your book list to your publisher and so on. I find it's a great way to just make the one call and handle all of the other pieces from there.
So your publisher model code would be something like this (note - your keys should actually match your json):
class Entities.Publisher extends Backbone.RelationalModel
urlRoot: "publishers"
relations: [
{
type: Backbone.HasMany
key: "bookLists"
relatedModel: Entities.BookList
reverseRelation:
key: 'publisher'
includeInJSON: 'id'
},
{
type: Backbone.HasMany
key: "videoLists"
relatedModel: Entities.VideoList
reverseRelation:
key: 'publisher'
includeInJSON: 'id'
}
]

Backbone.js Dynamic model creation based on JSON received from the server

I am trying to create a backbone client side application. I am receiving a list of json objects from the server on startup that will be a list of the possible tables exposed from the server, with their structure. E.g. Customers, Orders, Invoices, Employees
I want to create the models, collections and views dynamically based on the data I receive from the server.
Only when I receive the json on load will I know what the models should be and what the relationships between the models should be.
E.g. Customers structure might be Id, CustomerName, Address, Contact Numbers.
Order Structure might be Id, CustomerId, OrderDate, Amount
etc
By building Models, collections, views, controllers dynamically, I could in theory on startup point at another server who might give me a totally different set of tables e.g. : Movies, Actors etc.. with their structures.
Also, if additional fields are added I don't have to change the client side code again. E.g. Customer table might include a new field called ContactPerson
Please assist me as all the examples I saw on backbone is all based on statically defining the models on the client side up front. So create a model and collections and views for Customers, Orders, Invoices, Employees etc. etc.
Best wishes,
Andy
As already mentioned in the comments, Backbone models are dynamic by nature. So this is perfectly valid for example:
// A example dataset, this could be returned as JSON from the server
var jsonDataA = [
{
name: "Foo",
title: "Bar"
},
{
name: "a",
title: "b"
}
],
// A different example dataset
jsonDataB = [
{
make: "X",
model: "Y"
},
{
make: "Z",
model: "ZZ"
}
],
MyModel = Backbone.Model.extend({
/* Empty Model definition */
}),
MyCollection = Backbone.Collection.extend({
model: MyModel
}),
collection = new MyCollection();
collection.reset(jsonDataA);
console.log(collection.models);
collection.reset(jsonDataB);
console.log(collections.models);
Here I have reused the same Collection and Model definition to store completely different datasets.
One part is the raw data, the other part is its relations. You need to transport the metadata also, which contains the types and their relations. Model attributes will be populated automatically.
From your metadata a simple object can be constructed, where the keys describe one entity, for example:
var entites = {};
entities["Customer"] = Backbone.Model.extend({
/* Model definition based on metadata */
});
var parametersFromServer = {name: "John Doe"};
var customer = new entities["Customer"](parametersFromServer);
For building relations I would recommend using BackboneRelational plugin.

Dynamic Model with ExtJS 4

With ExtJS 3.x, I was able to use the "fields" property of a Store, but it seems with ExtJS 4 I have to absolutely use a Model. It's fine, but in my case, it's not a static Model, and I need to define the fields on the fly and sometimes to change them.
I could re-create a Model, but I need to use a different name as it's apparently not possible to modify an exisiting Model, neither delete it. If I try to use Ext.regModel with the same name, ExtJS crashes.
Thanks for your help!
4.1 UPDATE:
As an update... in 4.1 there is now a static method setFields which can be used to define the model prototype fields. It works well in a controller's init method.
When I did this, I wanted to have some static fields defined in the model class and then set some more dynamically. Unfortunately the new setFields method replaces all fields with the argument, it was easy enough to handle though.
This example uses the MVC pattern where my model and store are included in the controller's model array and store array (providing me with the handy getters used below):
Ext.define('ST.controller.Main', {
extend: 'Ext.app.Controller',
models: ['User', 'Reference'],
stores: ['CurrentUser', 'PermissionRef'],
views: ['MainPanel'],
init: function() {
var me = this;
me.getPermissionRefStore().on('load', function(store, records) {
var model = me.getUserModel();
// this returns the static fields already defined
// in my User model class
fields = model.prototype.fields.getRange();
// add the permission options (dynamic fields) to the static fields
Ext.each(records, function(permission) {
fields.push({name: permission.get('name'), type: 'bool'});
});
// 4.1 method to update the User model fields
model.setFields(fields);
// now load the current user (it will use the updated model)
me.getCurrentUserStore().load();
});
}
});
The User model and CurrentUser store are created exactly like regular, non-dynamic models and stores would be and included in their respective controller arrays, the 'User' model is simply missing the dynamic fields which are added as shown above.
I also went into that problem. I have a service which is responsible for fetching metadata from the server and adapting the models and stores to this metadata.
I therefore defined an empty model and configured the store to use this model.
When the meta data is processed, I add the new/additional fields to the prototype of the model like this (metaDataStore is the store containing the meta data, model is the model which can be obtained from the model manager):
var fields = [];
metaDataStore.each(function(item) {
fields.push(Ext.create('Ext.data.Field', {
name: item.get('field')
}));
});
model.prototype.fields.removeAll();
model.prototype.fields.addAll(fields);
When I then call load on a store using this model or create new model instances the new fields are processed correctly.
Here's a very simple example. Just use a normal Ext.data.Store but instead of a model, specify the fields property:
// you can specify a simple string ('totally')
// or an object with an Ext.data.Field ('dynamic')
var fields = ['totally', {name : 'dynamic', type : 'string'}];
var newStore = new MyApp.store.Object({
fields : fields
// other options like proxy, autoLoad...
});
Don't specify a model property - it seems that it would override the fields property.
I also wanted to change the columns and content of an existing grid dynamically:
// reconfigure the grid to use the new store and other columns
var newColumns = [
{header: 'Totally', dataIndex: 'totally'},
{header: 'Dynamic', dataIndex: 'dynamic'}
];
myGrid.reconfigure(newStore, newColumns);
From the Ext JS 4 documentation about the "fields" property of Ext.data.Store:
This may be used in place of
specifying a model configuration. The
fields should be a set of
Ext.data.Field configuration objects.
The store will automatically create a
Ext.data.Model with these fields. In
general this configuration option
should be avoided, it exists for the
purposes of backwards compatibility.
For anything more complicated, such as
specifying a particular id property or
assocations, a Ext.data.Model should
be defined and specified for the model
config.
So be careful - Sencha may remove it in the future.

Resources