简体   繁体   中英

How to insert an auto-generated id in a Postregsql entity table in another table's ID

I have an entity table that I want to auto-generate data from to use as FK in other tables. The generated Id will become the PK in the other tables.

My Tables

Users table with user_Id (PK), and other columns such as firstname , lastname , email , password etc.

Entry table is the Entity table with one entry_Id (PK) column.

Article table will use the auto-generated entry_Id in Entry table above as PK with other columns such as title , authorId , category , created_Date .

Photo table will use the auto-generated entry_Id in Entry table above as PK with other columns such as title , imageurl , authorId (FK), created_Date .

Comment table will use comment_Id as PK with the auto-generated entry_Id in Entry table above as FK to form a composite key. Other columns include user_Id as FK from Users table, comment , created_Date .

Flag table will use flag_Id as PK with the auto-generated entry_Id in Entry table above as FK to form a composite key. Other columns include user_Id as FK from Users table, flag_type .

What I Want To Do

I want my query to auto-generate the entry_Id for entry when someone submit a form and automatically used the generated id in other tables such as Article , Photo , Comment and Flag .

When I hard coded the values, the Article and Photo table is accepting one entry_Id for multiple rows.

I saw something like this but I am not sure if it's what I want.

START TRANSACTION;
INSERT INTO foo (auto,text)
    VALUES(NULL,'text');       
INSERT INTO foo2 (id,text)
    VALUES(LAST_INSERT_ID(),'text'); 
COMMIT TRANSACTION;

Is there a script I can use to make the auto-generated id in my entity table re-usable in other tables?

As commented by wildplasser, since version 9.1 Postgres has a nice feature that combines a cte with the returning keyword, which allows you to do what you want.

Here is an example based on your pseudo-code:

with foo_row as (insert into foo (text) values ('text') returning foo_id)
insert into foo2 (foo_id) select foo_id from foo_row

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM