3 ms·
You can build data models that correspond pretty well to OOP. Lets say you have a superclass named Person, with primary key person_pk. You can then, in the dat
by trashtester 5y ago
You can build data models that correspond pretty well to OOP.
Lets say you have a superclass named Person, with primary key person_pk. You can then, in the data model, implement polymorphism by creating a sub-class-table, for instance CustomerPerson, by giving it the same person_pk as primary key, where the same person has the same value for the primary key.
In this case, every person should be in the Person table, but only customers should be in the CustomerPerson table.
If person is implemented in your OOP by inheritance, you can leave shared fields (variables) in the Person table, and only add additional fields to the CustomerPerson table. Your program can then instantiate Person objects by simply using the Person table, and CustomerPerson objects by joining by person_pk.
If Person is just an abstract interface, you may want to have it only contain the primary key, and have all fields in the subclass CustomerPerson table. In this case, you could join CustomerPerson directly with some address-table, for instance, by person_pk, without going through the superclass (Person).
(And if you need it to also generalize to companies, you could have both Company and Person be subclasses of a class named Subject, and use subject_pk as primary key in Subject, PersonSubject, CompanySubject, PersonCustomerSubject and CompanyCustomerSubject and even CustomerSubject)
The approach above works better in my experience, than having subclasses have their own primary keys, especially if you read more than write to the db, as it can drastically reduce the number of joins you need to do, and because it prevents one-to-many relationships between subclass and superclass. (A limitation would be if you are not able to recognize a shared primary key across subclasses when creating an object.)
- mulmen 5y agoPostgres actually has a concept of inherited tables to make this pattern explicit in the DDL. Although I’m not sure the PK uniqueness constraint is enforced. https://www.postgresql.org/docs/14/ddl-inherit.html https://www.postgresql.org/docs/14/ddl-inherit.html