Documentation Index
Fetch the complete documentation index at: https://docs.sqd.dev/llms.txt
Use this file to discover all available pages before exploring further.
Entity relations and inverse lookups
The term “entity relation” refers to the situation when an entity instance contains an instance of another entity within one of its fields. Type-wise this means that some entity (called the owning entity) has a field of a type that is some other, non-owning entity. Within the database, this is implemented as an (automatically indexed) foreign key column within the table mapped to the owning entity. AfieldName entity-typed field will map to a column named field_name_id.
One-to-one and one-to-many relations are supported by Typeorm. The “many” side of the one-to-many relations is always the owning side. Many-to-many relations are modeled as two one-to-many relations with an explicit join table.
An entity relation is always unidirectional, but it is possible to request the data on the owning entity from the non-owning one. To do so, define a field decorated @derivedFrom in the schema. Doing so will cause the Typeorm code generated by squid-typeorm-codegen and the GraphQL API served by squid-graphql-server to show a virtual (that is, not mapping to a database column) field populated via inverse lookup queries.
The following examples illustrate the concepts.
One-to-one relations
User entity references Account and owns the one-to-one relation. This is implemented as follows:
- On the database side: the
accountproperty of theUserentity maps to theaccount_idforeign key column of theusertable referencing theaccounttable. - On the TypeORM side: the
accountproperty of theUserentity gets decorated with@OneToOneand@JoinColumn. - On the GraphQL side: sub-selection of the
accountproperty is made available inuser-related queries. Sub-selection of theuserproperty is made available inaccount-related queries.
Unlike for the many-to-one case, the codegen will not add a virtual reverse lookup property to the TypeORM code for one-to-one relations. You can add it manually:If you are using this feature, please let us know at the SquidDevs Telegram channel.
src/model/generated/account.model.ts
Many-to-one/One-to-many relations
Transfer defines owns the two relations and Account defines the corresponding inverse lookup properties. This is implemented as follows:
- On the database side: the
fromandtoproperties of theTransferentity map tofrom_idandto_idforeign key columns of thetransfertable referencing theaccounttable. - On the TypeORM side: properties
toandfromof theTransferentity class get decorated with@ManyToOne. PropertiestransfersToandtransfersFromdecorated with@OneToManyget added to theAccountentity class. - On the GraphQL side: sub-selection of all relation-defined properties is made available in the schema.
