Search code examples
sqlpostgresqltypeorm

SQL. How to insert data into two tables at a time when one related to another with a foreign key


I have two tables:

Attr.type_id is a foreign key to Type.id

enter image description here

Let's assume I want to save the following data:

{
  name: 'cats',
  attributes: ['breed', 'weight']
}

I expect this after saving:

enter image description here

How do I properly write an insert query?

I know I can't insert into two tables at the same time. Should I use transactions? Or maybe there is a simple way because this seem trivial but in fact it's not.

If you know how to do that using TypeORM, it will be grateful as well

Update: I'm using PostgreSQL


Solution

  • As type table is the master table having primary key insert the id first then insert in the attr table. In this order constraint integrity would be mantained as foreign key always refers its parent table for a particular attribute. Hence in your case id is the one which needs to be referred in the type table and then insert in the attr table.