14

I am new to graphql hasura and i'm having this issue how to update multiple rows in one table, because usually i update only one row per table.

i want to update multiple rows in a dynamic way

I have for example existing rows data.

id: 1, name: 'rosie', age: 12
id: 2, name: 'jane', age: 20
id: 3, name: 'rafaela', age: 25

and I want to edit the 2 rows only.

id: 1, name: 'rosie update', age: 12
id: 2, name: 'jane update', age: 21

i have an array of users. it can be 1 or more than 1 users that will be updated.

const users = [
{id: 1, name: 'rosie update', age: 12}.
{id: 2, name: 'jane update', age: 21}
];

mutation update_article {
  update_user(
    where: {id: {_eq: users[0].id}},
    _set: {
      name: users[0].name,
      age: users[0].age
   }
  ) {
    affected_rows
  }
}

expected output should be:

want to have mutation code in dynamic way not static.

id: 1, name: 'rosie update', age: 12
id: 2, name: 'jane update', age: 21
id: 3, name: 'rafaela', age: 25
rj.learn
  • 645
  • 1
  • 6
  • 14

2 Answers2

20

Reading the documentation mutation, you could use insert instead of update that can handle multiple objects managing the conflict behaviour.

In your example the mutation could be done with:

mutation update_article {
  insert_user(objects: [
         {id: 1, name: "rosie update", age: 12},
         {id: 2, name: "jane update", age: 21}
      ],
      on_conflict: {
        constraint: user_id_key,
        update_columns: [name, age]
      }
  ) {
    affected_rows
  }
}

As id values already exist, it will update fields name and age.

mpromonet
  • 11,326
  • 43
  • 62
  • 91
  • 3
    This will only work if the user has id-insert permissions (which she shouldn't). Handling primary keys is the job of the database. – Friedrich Oct 28 '21 at 16:37
3

Run multiple updates with different conditions (V2.10.0)

  1. https://github.com/hasura/graphql-engine/releases/tag/v2.10.0
  2. https://hasura.io/docs/latest/mutations/postgres/update/#multiple-updates
mutation update_many_articles {
  update_article_many (
    updates: [
      {
        where: {rating: {_lte: 1}},
        _set: {is_published: false}
      },
      {
       where: {rating: {_gte: 4}},
        _set: {is_published: true}
      }
    ]
  ) {
    affected_rows
  }
}
Aathi
  • 2,599
  • 2
  • 19
  • 16