new to ember js, and working on an app using ember-data. If I test with same data using FixtureAdapter, everything populates in the html template ok. When I switch to RESTAdapter, the data looks like it's coming back ok, but the models are not being populated in the template? Any ideas? Here's the code:
App.Store = DS.Store.extend({
revision:12,
//adapter: 'DS.FixtureAdapter'
adapter: DS.RESTAdapter.extend({
url:'http://bbx-dev.footballamerica.com/builderapirequest/bat'
})
});
App.Brand = DS.Model.extend({
name: DS.attr('string'),
numStyles: DS.attr('string'),
vendorId: DS.attr('string')
});
App.BrandsRoute = Ember.Route.extend({
setupController:function(controller){
},
model:function(){
return App.Brand.find();
}
});
And here is the data coming back, but not being inserted into the template!
returnValue: [{numStyles:1, name:Easton, vendorId:6043}, {numStyles:1, name:Louisville Slugger, vendorId:6075},…]
0: {numStyles:1, name:Easton, vendorId:6043}
1: {numStyles:1, name:Louisville Slugger, vendorId:6075}
2: {numStyles:1, name:Rawlings, vendorId:6109}
3: {numStyles:7, name:BWP Bats , vendorId:6496}
4: {numStyles:1, name:DeMarini, vendorId:W002}
status: "ok"
And here is the template:
{{#each brand in model.returnValue }}
<div class="brand-node"{{action select brand}}>
<h2>{{brand.name}}</h2>
<p>{{brand.numStyles}} Styles</p>
</div>
{{/each}}
Any help would be greatly appreciated! I'm not getting any errors, and the data seems to be coming back ok, just not getting into the template. Not sure if the returned dataset needs "id" param?
I am also using the Store congfig to alter the find() from plural to singular:
DS.RESTAdapter.configure("plurals", {
brand: "brand"
});
The way the API was written, its expecting "brand" and not "brands"... maybe its something to do with this??
Thanks in advance.
You have stated:
Not sure if the returned dataset needs "id" param?
Yes you are guessing right, you data coming back from the backend need's an id field set. And if the id field name is different then id you should also define this in ember like so:
App.Store = DS.Store.extend({
revision:12,
//adapter: 'DS.FixtureAdapter'
adapter: DS.RESTAdapter.extend({
url:'http://bbx-dev.footballamerica.com/builderapirequest/bat'
}),
serializer: DS.RESTSerializer.extend({
primaryKey: function (type) {
return '_my_super_custom_ID'; // Only needed if your id field name is different than 'id'
}
})
});
I suppose your Fixtures have an id defined thus it works, right?
Note: you don't need to define the id field at all explicitly, ember add's automatically the id field to a model, so your model is correct.
Here a website that is still a WIP but can be good reference for this conventions
and as stated there:
The document MUST contain an id key.
And this is how your JSON should look like for a collection of records:
{
"brands": [{
"id": "1",
"numStyles": "1",
"name": "Easton",
"vendorId" :"6043"
}, {
"id": "2",
"numStyles": "4",
"name": "Siemens",
"vendorId": "6123"
}/** and so on**/]
}
Note: as you have shown you JSON root is called returnValue this should be called brand or brands if you are not adapting the plurals. See here for reference for the JSON root I'm talking about.
Hope it helps
Related
Let's say I have an API, by calling it we get a list of posts, for each post I want to send a value whether that post is editable or not by the logged-in user in the response. so for that I'm using Case statement from SQLAlchemy and based on the logged-in user ID I'm returning true or false
The code looks like below
is_editable_expr = case(
[
(Post.user_id == current_user.id, True),
],
else_=False,
).label("is_editable")
data = db_session.query(Post, is_editable_expr).order_by(Post.created_at.desc()).join(User).all()
I'm using FastAPI and when it tries to serialize the data it fails because the value returned by this is ORM looks like
[(<Post title=Todo title description=A short description about your todo>, False), ...]
here the post model instance is inside the tuple and is_editable is directly accessible. the Post pydantic model looks like this
class Post(BaseModel):
id: int
title: str,
description: str,
user: User
is_active: bool
is_editable: bool
class Config:
orm_mode = True
since the orm instance itself is inside tuple while serializing it's failing and cannot access title/descriptions etc. I want my response to be a list of Post and it should look like this
[
{
"title":"title name",
"description":"some long description",
"is_editable":true
},
...
]
Can anyone please advice or suggest how can I make it work. Thanks in advance.
That is happening because of your query definition: db_session.query(Post, is_editable_expr)
So basically the second item in the tuple is your is_editable expression
I would rather avoid doing it in the database and would do a simple loop to do it on the server:
data = (db_session.query(Post)
.order_by(Post.created_at.desc())
.join(User)
.all())
for post in data:
post.is_editable = post.user_id == current_user.id
I'm trying to update a one to many relationship in Prisma. My schema looks like this
model A_User {
id Int #id
username String
age Int
bio String #db.VarChar(1000)
createdOn DateTime #default(now())
features A_Features[]
}
model A_Features {
id Int #id #default(autoincrement())
description String
A_User A_User? #relation(fields: [a_UserId], references: [id])
a_UserId Int?
}
I'm trying to add a couple of new features to user with id: 1, or update them if they are already there.
I'm trying doing something like
const post = await prisma.a_User.update({
where: { id: 1},
data: {
features: {
upsert: [
{ description: 'first feature'},
{ description: 'second feature'}
]
}
}
})
The compiler isn't happy, it tells me
Type '{ features: { upsert: { description: string; }[]; }; }' is not assignable to type '(Without<A_UserUpdateInput, A_UserUncheckedUpdateInput> & A_UserUncheckedUpdateInput) | (Without<...> & A_UserUpdateInput)'.
Object literal may only specify known properties, and 'features' does not exist in type '(Without<A_UserUpdateInput, A_UserUncheckedUpdateInput> & A_UserUncheckedUpdateInput) | (Without<...> & A_UserUpdateInput)'.ts(2322)
index.d.ts(1572, 5): The expected type comes from property 'data' which is declared here on type '{ select?: A_UserSelect; include?: A_UserInclude; data: (Without<A_UserUpdateInput, A_UserUncheckedUpdateInput> & A_UserUncheckedUpdateInput) | (Without<...> & A_UserUpdateInput); where: A_UserWhereUniqueInput; }'
(property) features: {
upsert: {
description: string;
}[];
}
I can't work out how to do it nor I can find clear help in the documentation. Any idea on how to implement it or where I can find some examples?
I'm providing my solution based on the clarifications you provided in the comments. First I would make the following changes to your Schema.
Changing the schema
model A_User {
id Int #id
username String
age Int
bio String #db.VarChar(1000)
createdOn DateTime #default(now())
features A_Features[]
}
model A_Features {
id Int #id #default(autoincrement())
description String #unique
users A_User[]
}
Notably, the relationship between A_User and A_Features is now many-to-many. So a single A_Features record can be connected to many A_User records (as well as the opposite).
Additionally, A_Features.description is now unique, so it's possible to uniquely search for a certain feature using just it's description.
You can read the Prisma Guide on Relations to learn more about many-to-many relations.
Writing the update query
Again, based on the clarification you provided in the comments, the update operation will do the following:
Overwrite existing features in a A_User record. So any previous features will be disconnected and replaced with the newly provided ones. Note that the previous features will not be deleted from A_Features table, but they will simply be disconnected from the A_User.features relation.
Create the newly provided features that do not yet exist in the A_Features table, and Connect the provided features that already exist in the A_Features table.
You can perform this operation using two separate update queries. The first update will Disconnect all previously connected features for the provided A_User. The second query will Connect or Create the newly provided features in the A_Features table. Finally, you can use the transactions API to ensure that both operations happen in order and together. The transactions API will ensure that if there is an error in any one of the two updates, then both will fail and be rolled back by the database.
//inside async function
const disconnectPreviouslyConnectedFeatures = prisma.a_User.update({
where: {id: 1},
data: {
features: {
set: [] // disconnecting all previous features
}
}
})
const connectOrCreateNewFeatures = prisma.a_User.update({
where: {id: 1},
data: {
features: {
// connect or create the new features
connectOrCreate: [
{
where: {
description: "'first feature'"
}, create: {
description: "'first feature'"
}
},
{
where: {
description: "second feature"
}, create: {
description: "second feature"
}
}
]
}
}
})
// transaction to ensure either BOTH operations happen or NONE of them happen.
await prisma.$transaction([disconnectPreviouslyConnectedFeatures, connectOrCreateNewFeatures ])
If you want a better idea of how connect, disconnect and connectOrCreate works, read the Nested Writes section of the Prisma Relation queries article in the docs.
The TypeScript definitions of prisma.a_User.update can tell you exactly what options it takes. That will tell you why the 'features' does not exist in type error is occurring. I imagine the object you're passing to data takes a different set of options than you are specifying; if you can inspect the TypeScript types, Prisma will tell you exactly what options are available.
If you're trying to add new features, and update specific ones, you would need to specify how Prisma can find an old feature (if it exists) to update that one. Upsert won't work in the way that you're currently using it; you need to provide some kind of identifier to the upsert call in order to figure out if the feature you're adding already exists.
https://www.prisma.io/docs/reference/api-reference/prisma-client-reference/#upsert
You need at least create (what data to pass if the feature does NOT exist), update (what data to pass if the feature DOES exist), and where (how Prisma can find the feature that you want to update or create.)
You also need to call upsert multiple times; one for each feature you're looking to update or create. You can batch the calls together with Promise.all in that case.
const upsertFeature1Promise = prisma.a_User.update({
data: {
// upsert call goes here, with "create", "update", and "where"
}
});
const upsertFeature2Promise = prisma.a_User.update({
data: {
// upsert call goes here, with "create", "update", and "where"
}
});
const [results1, results2] = await Promise.all([
upsertFeaturePromise1,
upsertFeaturePromise2
]);
Let’s say I have foo and I make it include bar model,They are many to many relationship.
While bar model contains a column called clients, which is an array in nodejs.
foo.findAll({
where : where,
include : [{ model: bar}]
})
How should I use foo.findAll to get all data which bar must be an empty array.
You can simply Do it like this I am suggesting this because your question is unclear
foo.findAll({
where: where,
include: [{
model: bar,
where: { name: { [Op.is]: null } }
}]
})
above code will return data of model bar where name as no value or the field is null
I've got the following models associated with sequelize.
Event hasMany Characters through characters_attending_boss
Boss hasMany Characters through characters_attending_boss
Characters hasMany Event through characters_attending_boss
Characters hasMany Boss through characters_attending_boss
These tables are successfully joined and I can retrieve data from them. But when I retrieve the JSON-results the name of the through model gets added to each object, like this:
{
id: 1
title: "title"
-confirmed_for: [ //Alias for Event -> Character
-{
id: 2
character_name: "name"
-confirmed_for_boss: [ // Alias for Boss -> Character
-{
id: 9
name: "name"
-character_attending_event: { // name of through-model
event_id: 1
char_id: 2
}
}
]
-character_attending_boss: { // name of through-model
event_id: 1
char_id: 2
}
}
So I'm looking for a way to hide these "character_attending_boss" segments if possible, preferably without altering the results post-fetch.
Is this possible?
Same issue is solved here: https://github.com/sequelize/sequelize/issues/2541
For me adding through: {attributes: []} to include block works well on Sequelize 2.0
Pass { joinTableAttributes: [] } to the query.
I'm using extJS version 4.0 to generate a entry form. On that form there is a save button that sends all the fielddata to php via ajax. As transfer protocol for the data itself I'm using json.
As I need to make a dynamical (general) routine for processing this data (as that one form won't be the only form in that project) I would need that json data grouped somehow. One of the requirements I have is that I need the "fieldnames" to be as they are (as I use the fieldnames I get transmitted to me to access the approopriate coloumns in the database in the automatic save routine).
My question here is is there any way to somehow group the data that is transmitted via json (thus that extJS groups it).
As a simplified example:
On the entryform I'm saving data for 2 tables (1. Person 2. bankaccount) which have the following fields shown on the form:
-firstname
-lastname
for person
and
-account number
-bank number
for bankaccount
(the stores are accordingly)
Is there a way with extJS to group this data acordingly, thus generate something like this?
{"person":[{"firstname": "Mark", "lastname":"Smith"}],"bankaccount":[{"account number":123112,"bank number":1A22A1}]}
Currently I'm getting something like this:
{"firstname": "Mark", "lastname":"Smith","account number":123112,"bank number":1A22A1}
Both person and bankaccount are in their separate stores.
Tnx.
Well, you've two stores: one for 'person' and one for 'bankaccount'.
Ext.define ('Person', {
extend: 'Ext.data.Model' ,
fields: ['firstname', 'lastname']
});
Ext.define ('BankAccount', {
extend: 'Ext.data.Model' ,
fields: ['accountnumber', 'banknumber']
});
var personStore = Ext.create ('Ext.data.Store', {
model: 'Person' ,
data: [
{firstname: 'foo', lastname: 'bar'} ,
{firstname: 'zoo', lastname: 'zar'} ,
{firstname: 'too', lastname: 'tar'} ,
{firstname: 'goo', lastname: 'gar'} ,
{firstname: 'moo', lastname: 'mar'}
]
});
var bankAccountStore = Ext.create ('Ext.data.Store', {
model: 'BankAccount' ,
data: [
{accountnumber: 10000, banknumber: 10000} ,
{accountnumber: 20000, banknumber: 20000} ,
{accountnumber: 30000, banknumber: 30000} ,
{accountnumber: 40000, banknumber: 40000} ,
{accountnumber: 50000, banknumber: 50000}
]
});
Then, you want to dump these stores as JSON. No problem!
Make a container (jsonData) and then fill it up with your stores:
var jsonData = {
person: [] ,
bankaccount: []
};
personStore.each (function (person) {
jsonData.person.push (person.data);
});
bankAccountStore.each (function (bank) {
jsonData.bankaccount.push (bank.data);
});
console.log (Ext.JSON.encode (jsonData));
And this is the output on the console:
{"person":[{"firstname":"foo","lastname":"bar"},{"firstname":"zoo","lastname":"zar"},{"firstname":"too","lastname":"tar"},{"firstname":"goo","lastname":"gar"},{"firstname":"moo","lastname":"mar"}],"bankaccount":[{"accountnumber":10000,"banknumber":10000},{"accountnumber":20000,"banknumber":20000},{"accountnumber":30000,"banknumber":30000},{"accountnumber":40000,"banknumber":40000},{"accountnumber":50000,"banknumber":50000}]}
Is that what you've requested?
Here's the fiddle