DEV Community

Ibrahim EL-Sanosi
Ibrahim EL-Sanosi

Posted on

Postgres Database Parent/Children relationship

This is a senario:

I have got a object let's say a cat. For example when I insert the cat 4 details to database, I can add children to cat 4, lets say cat 1, 2 and 3.

In web page, when I click on cat 4 link, I need to open new page with details of cat 4 plus cat 1, 2 and 3.

I am not wondering about the frontend implementation, I onloy want to know how can this be designed in database. I do not think this is related to inhertance since we are dealing with same type of object which is a cat.

I can make it simple by creating a array field in cat table that contains children's ids, but I am not sure if this is the best solution. Or It could be better way to implement this in Postgres database.

Top comments (2)

Collapse
 
emtiajium profile image
Emtiaj Hasan • Edited

cat table

id int4 primary key
sex varchar
parentId int4

"parentId" is the foreign key. It contains in the cat table and it refers to the same cat table.

That is how it can be achieved.

Collapse
 
emtiajium profile image
Emtiaj Hasan • Edited

Insert into cat (id, sex) values(1, 'male');
Insert into cat (id, sex) values(2, 'female');
Insert into cat (id, sex, "parentId") values(3, 'male', 1);