I am using Hasura with my Flutter Application..
I have 2 tables: tasks and categories
tasks comprises of id, task_name, category_id, status.
category comprises of id, category_name, user_id, color.
What I want to do is get the name of the category that the task belongs to using the category_id
What I thought of is:
query getTasks($user_id: String!) {
tasks(where: user_id: {_eq: $user_id}}, order_by: {created_at: desc}) {
category_id
name
}
category_by_pk(id: tasks['category_id']){
name
}
}
The part that is tasks['category_id'] being passed as a query variablele is giving an error
Any idea how can I do this?
Thanks in advance
Have you tracked a relationship in Hasura between tasks and categories? Normally with GraphQL you would just traverse the relationship to get information about the related entity:
query getTasks($user_id: String!) {
tasks(where: user_id: {_eq: $user_id}}, order_by: {created_at: desc}) {
name
category { // Just follow the relationship
id
name
}
}
}
Related
I have the following set of GORM models, with 2 orders of one-to-many relations:
type Order struct {
ID string `gorm:"column:id"`
ClientID string `gorm:"primaryKey;column:client_id"`
Name string `gorm:"column:name"`
Albums []Album `gorm:"foreignKey:RequestClientID"`
}
type Album struct {
AlbumID string `gorm:"primaryKey;column:album_id"`
RequestClientID string `gorm:"foreignKey:ClientID;column:request_client_id"`
Pictures []Picture `gorm:"foreignKey:AlbumID"`
}
type Picture struct {
PictureID string `gorm:"primaryKey;column:picture_id"`
AlbumID string `gorm:"foreignKey:AlbumID;column:album_id"`
Description string `gorm:"column:description"`
}
When I attempt to insert data as follows, I get the error pq: insert or update on table "albums" violates foreign key constraint "fk_orders_albums".
test := Order{
ID: "abc",
ClientID: "client1",
Name: "Roy",
Albums: []Album{
{
AlbumID: "al_1",
Pictures: []Picture{
{
PictureID: "pic_1",
Description: "test pic",
},
},
},
},
}
gormDB.Save(&test)
I followed the solution on this similar question, but can't seem to get it to work: Golang: Gorm Error on insert or update on table violates foreign key contraint
Based on your entity model, Your schema would be like this:
Orders table is parent table, didn't depend to any table
Albums table has foreign key request_client_id which refer to orders table column client_id
Picture table has foreign key album_id which is refer to albums table column album_id
Based on my exploration in gorm documentation here, object in struct will be examine as first association. so, your struct will execute insert to albums first which it violate foreign key schema (expect: insert to orders table should be executed before albums).
But if you want to force using your schema, you can use gorm Association feature.
Here is the idea of using Association:
Expected Query in high level:
Insert to orders table
Insert to albums table
Insert to pictures table
Association Ideas:
Let Albums field value in Orders struct empty
Append Association Albums to Orders model
Since there have another association in Albums, use configuration FullSaveAssociation
Here is the following code:
picture := []Picture{
{
PictureID: "pic_1",
Description: "test pic",
},
}
albums := []Album{
{
ID: "al_1",
Pictures: picture,
RequestClientID: "",
},
}
orders := Order{
ID: "abc",
ClientID: "client1",
Name: "Roy",
}
if err := gormDB.Save(orders).Error; err != nil {
return
}
if err := gormDB.Session(&gorm.Session{FullSaveAssociations: true}).Model(&orders).Association("Albums").Append(albums); err != nil {
return
}
Full code could be found here:
Came across the solution I was looking for while looking into the great answer #giyuu provided. Since I had not saved the item before, I needed to use GORM's Create method:
err = gormDB.Create(&test).Error
Then, when I want to perform an update on any of these values, I use the Save method, with FullSaveAssociations enabled:
err = gormDB.Session(&gorm.Session{FullSaveAssociations: true}).Save(&test).Error
I want to get user data with relation sorted but with this code it just sort the user but I want to sort data that have relation with user I'm using eager, could any one help me ?
getUerWithId(pramas: string): Observable<userEntity[]> {
return from(this.userRepository.find({
where: [
{ id: pramas }
],
order:{
id:'DESC'
}
}))
}
With the repository, I don't know if it is possible, but you can try with query builder to get ordered relations. Follow example bellow:
this.userRepository.createQueryBuilder()
.innerJoinAndSelect("User.notification", "Notification")
.orderBy({'Notification.createdAt': 'DESC'})
.where("User.id = :id", {
id: Number(id),
})
.getOne();
Remember to put the right relationship for your entity, and right names for your properties.
I have a group of checkboxes for skin concerns. Users can check/uncheck them before submitting, which means the set of skin concerns submitted can be different every time.
I modeled it in Prisma schema as an 'explicit' many-to-many relation.
model User {
id String #id #default(cuid())
name String?
nickname String? #unique
...
skinConcerns SkinConcernsForUsers[]
...
}
model SkinConcern {
id Int #id #default(autoincrement())
name String #unique
user SkinConcernsForUsers[]
}
model SkinConcernsForUsers {
user User #relation(fields: [userId], references: [id])
userId String
skinConcern SkinConcern #relation(fields: [skinConcernId], references: [id])
skinConcernId Int
##id([userId, skinConcernId])
}
Then, SkinConcerns table is seeded with the following values, using prisma.skinConcern.createMany:
"ACNE",
"DRYNESS",
"OILY_SKIN",
"PIGMENTATION",
"REDNESS",
"WRINKLES",
SkinConcerns in Update mutation input comes in the form of array of strings, e.g. ["PIGMENTATION", "REDNESS"].
I want to update the skin concerns for users (SkinConcernsForUsers) from the prisma.user.update query, but it's tricky, since I'm not merely creating SkinConcerns, but have to connect to existing set of skin concerns.
I've tried directly setting skinConcerns in user, like
await prisma.user.update({
where: { nickname },
data: {
// ... other user data
skinConcerns: {
set: [
{
skinConcern: {
connect: { name: "PIGMENTATION" },
},
},
{
skinConcern: {
connect: { name: "REDNESS" },
},
},
],
},
// ... other user data
}
});
among many other things, but of course this is not a correct argument and fails with error
Unknown arg `connect` in data.skinConcerns.update.0.where.connect for type SkinConcernsForUsersWhereUniqueInput. Did you mean `select`?
Argument data for data.skinConcerns.update.0.data is missing.
Unknown arg `connect` in data.skinConcerns.update.1.where.connect for type SkinConcernsForUsersWhereUniqueInput. Did you mean `select`?
Argument data for data.skinConcerns.update.1.data is missing.
Is there a way to do this? Is it even possible to update this in prisma.user.update?
I guess I could directly update SkinConcernsForUsers. In that case, should I just delete all rows associated to the user that are not in the user input ["PIGMENTATION", "REDNESS"], then create rows that don't already exist? What will it look like in prisma code?
First I would change your schema for SkinConcern. The id field is not necessary and will create complications in queries (you would needlessly need to map each name to id when trying to connect/disconnect records.
The name field is sufficient as the primary key, as it is always unique for a certain record.
The changed schema looks like this
model SkinConcern {
name String #id // name is the new #id.
user SkinConcernsForUsers[]
}
model SkinConcernsForUsers {
user User #relation(fields: [userId], references: [id])
userId String
skinConcern SkinConcern #relation(fields: [skinConcernName], references: [name])
skinConcernName String
##id([userId, skinConcernName])
}
The query you want to do can be executed in two steps with the SkinConcernsForUsers model.
Step 1: Remove existing SkinConcernsForUsers records a user is connected to. These are no longer relevant, as you want to overwrite the previous selection.
Step 2: Create new SkinConcernsForUsers records with the new choices.
Here is what the code looks like
// step 1
await prisma.skinConcernsForUsers.deleteMany({
where: {
userId: "1",
},
});
// step 2
await prisma.skinConcernsForUsers.createMany({
data: [
{
userId: "1",
skinConcernName: "REDNESS",
},
{
userId: "1",
skinConcernName: "PIGMENTATION",
},
],
});
I was evaluating Hasura GraphQL engine + Postgres on Heroku and have run into a situation. I have 2 simple tables as shown below;
Employees
Payrolls
Employees table and Payrolls have a foreign key employees.ID -> payrolls.employee_id
Employees table has a foreign key with itself employees.manager_id -> employees.ID
I have gone ahead and "auto-tracked" all the relationships in Hasura.
What I want to calculate is the "sum of salaries" for all employees reporting. But, when I'm using the Hasura explorer to form the GQL query, I'm not able to find the "sum" aggregation under the "managed_employees_aggregate" subquery.
The expected output is
[
{
"full_name": "anuj gupta",
"total_reportee_salary": 4000
},
{
"full_name": "sowmya",
"total_reportee_salary": 2000
},
... "total_reportee_salary" for everyone else is 0
]
Any suggestions or references is really appreciated.
Answering my own question
As suggested by #Ambassel in the comments I ended up creating a view
create view reportee_total_vw AS
select
employees.manager_id,
SUM(payrolls.salary)
from
employees,
payrolls
where
payrolls.employee_id = employees."ID"
group by
employees.manager_id
Next I created a relationship named "reportee" that bound the "ID" from employees table with the "manager_id" from the view.
After that I could issue the underlying GQL query to get the result I wanted (although not in the exact format, but I can live with that :))
{
employees {
full_name
reportee {
total_reportee_salary:sum
}
}
}
I have Online Shop, where exists products and category. The product has in model field
category: {
type: Types.ObjectId,
ref: "Category",
required: [true, "Product category is required"]
},
and when i add new product select category ( in list exists ) and add id.
But if remove category, the products have categoryId which does not exists. Is it possible to implement the functionality that used in wordpress. For example if in wordpress i remove category, all posts who had this category, transfer in category uncategorized (This category create automatically and cannot be delete)
If I understood you correctly, you can use mongoose middlewares to "cascade deleting". So when a category is removed, you can to code that every product has now "Uncategorized"
You can use a pre hook when you call delete function and do something like this (not tested with your schema):
category.pre(/(?:delete|remove)/, function(next) {
var id = this.getQuery()._id; //get category _id
product.updateMany({
category: id
},{
$set:{
category:yourUncategorizedId
}
}).then(next()).catch(e => next(e))
})
So, in this case, a regex match is used to go into the hook.
This hook is called when a remove or delete function is called from category model. So, when a category is deleted, this hook will update all references by your uncategorizedId to ensure any product has a non-existing category reference.