How can I insert data into two different tables with a single request?

I just started using Strapi and I’m trying to figure out how I can with a single request insert data into one table, and then into another table that it has a relation to, with the same request. How can this be done?

I dont think you can do this easily. Maybe look into lifecycle methods - You could create a lifecycle method which creates a new row in the other table when you create the post in this table.

Though relations should already stay in sync so you shouldnt have to be updating relations

1 Like

Trying on this doc.
This maybe help you.
You can use

lifecycles: {
    async beforeCreate(data) {
      data.isTableFull = data.numOfPeople === 4;

That depends on your use case, if you are planning to update them through API then you can make a new service that will execute simultaneously two queries in two different models.

But if you are looking to achieve this from the Strapi’s Content manager than you should take a look at the lifecycles hooks (afterCreate, afterUpdate).

I’m still not getting the point for copying the same data in two different places, unless you copy it conditionally? But anyway you can filter data and there is no longer need for duplicating it over two models. Can you explain your use case?

Might be a little misunderstanding with what I’m trying to do.
So I want to create an object through the API. When i’m creating this object, i want to create multiples of a different object, which is related to the first object create, during the same request.

So with the request i create this “main” object and additionally multiples of another object related to the “main” object.

By object, do you mean just javascript objects? Or mean a row in db?
Share an example of what you have and what you are trying to achieve.

Second this, but confused on what is being asked.

1 Like

A row in the db.
And when I’m creating that row in the table, I would also like to create multiple rows in another table.

You can’t do this natively, you will likely need to create your own custom route/controller: