get a data of the last insert made

1

The case is as follows, I have two related tables in postgres, understand

Urbanization and Houses

in Urbanizacion we have the following data

idurb(PK-NoIncremental,varchar)| nombreurb | calle | idcasas(el campo
idcasas es una FK )

and in the other Houses we have the following data

idcasas(PK-NoIncremental-varchar) | numeroCasa | propietario

The problem is this, with INSERT I ordered to fill in first the Casas table which is completely filled by the user, his house number and the name of the owner and the ID of his house, however, I need to relate it to the first table so I need the idcasas q just just created to fill the table with the data idurb, nombreurb and street (q normally fill the user from the form), I also need to enter the id houses that were just created, to be able to relate it between both, I thought that by making normal inserts, the FK that would autocomplete itself, but it was not, is there any query that allows me to obtain a data that was just entered to insert it into another table?

These queries I do from nodeJS and the data I get from a form in angular.

    
asked by Jesus Cabrita 23.10.2018 в 04:11
source

1 answer

0

Get the id of a newly inserted autonomic pk

I guess you can do the insert in some way in your back-end (php, node.js, java, it does not matter the concept is the same).

What you can do to get the id is to use the RETURNING clause of the INSERT link .

Something like

INSERT INTO (numeroCasa, propietario) VALUES (77, 'María') RETURNING idcasa;

For example, node.js with pg would look like this:

var mi_numeroCasa=77;
var mi_propietario='María';
const result = await client.query('
    INSERT INTO (numeroCasa, propietario) VALUES ($1, $2) RETURNING idcasa
', [mi_numeroCasa, mi_propietario]);
var idcasa = result.rows[0].idcasa;
    
answered by 24.10.2018 / 19:07
source