New Jan 5, 2025

Amplify / React: Create item with child item in same data call

Libraries, Frameworks, etc. All from Newest questions tagged reactjs - Stack Overflow View Amplify / React: Create item with child item in same data call on stackoverflow.com

I have data objects that have a parent/child relationship. In the HTML form, the user adds info about both objects at the same time. Can I create both database objects at the same time in one call?

For example:

/amplify/data/resources.ts

const schema = a.schema({
  Person: a
    .model({
      name: a.string().required(),
      vehicles: a.hasMany("Vehicle", "personId")
    }).authorization((allow) => [allow.owner()]),
  Vehicle: a
    .model({
      vin: a.string().required(),
      personId: a.id(),
      person: a.belongsTo("Person", "personId")
    }).authorization((allow) => [allow.owner()]),
});

component

here I'd like to add a vehicle in the same call as the person. I know I can create the person, then create the vehicle. But can it be done in one call? Something like...

addPerson = async (dto: PersonCreateDto) => {
  let person: Schema["Person"]["type"] = {
    name: dto.name,
    vehicles: [
      { vin: dto.vin }
    ]
  }

await client.models.Person.create(person); }

Scroll to top