diff --git a/src/content/doc-surrealql/datamodel/references.mdx b/src/content/doc-surrealql/datamodel/references.mdx index 11b98345d..c58a66e91 100644 --- a/src/content/doc-surrealql/datamodel/references.mdx +++ b/src/content/doc-surrealql/datamodel/references.mdx @@ -113,5 +113,81 @@ SELECT * FROM comic_book; ] ``` -## Specifying linking tables and/or field names +## Specifying linking tables and field names +A field of type `references` can be further narrowed down to specify not just the table name, but also the field name of the referring record. + +In the comic book example, this can be used to keep track of which people own comic books (via a `comics` field on the `person` table), versus those who borrow those (via a separate `borrowed_comics`) field. Any `comic_book` can keep track of these separately by defining one field with the type `references`, and another field with the type `references`. + +```surql +DEFINE FIELD comics ON person TYPE option>> REFERENCE; +DEFINE FIELD borrowed_comics ON person TYPE option>> REFERENCE; +DEFINE FIELD owned_by ON comic_book TYPE references; +DEFINE FIELD borrowed_by ON comic_book TYPE references; + +CREATE person:one SET comics = [comic_book:one]; +CREATE person:two SET borrowed_comics = [comic_book:one]; +CREATE comic_book:one SET title = "Loki, God of Stories"; +SELECT * FROM comic_book; +``` + +```surql title="Output" +[ + { + borrowed_by: [ + person:two + ], + id: comic_book:one, + owned_by: [ + person:one + ], + title: 'Loki, God of Stories' + } +] +``` + +## Specifying deletion behaviour + +When keeping track of references, it is very likely that you will want some behaviour to happen when a reference is deleted. Take the following example of a `person` who owns a `comic_book`, which is later deleted. However, a follow-up `SELECT * FROM person` still shows the comic book. + +```surql +DEFINE FIELD comics ON person TYPE option>> REFERENCE; +DEFINE FIELD owned_by ON comic_book TYPE references; + +CREATE comic_book:one SET title = "Loki, God of Stories"; +CREATE person:one SET comics = [comic_book:one]; +DELETE comic_book:one; +SELECT * FROM person; +``` + +```surql title="Output" +[ + { + comics: [ + comic_book:one + ], + id: person:one + } +] +``` + +A query using `INFO FOR TABLE person` shows that the actual statement created using `REFERENCE` does not finish at this point, but includes the clause `ON DELETE IGNORE`. + +```surql +{ + events: {}, + fields: { + comics: 'DEFINE FIELD comics ON person TYPE option>> REFERENCE ON DELETE IGNORE PERMISSIONS FULL', + "comics[*]": 'DEFINE FIELD comics[*] ON person TYPE record REFERENCE ON DELETE IGNORE PERMISSIONS FULL' + }, + indexes: {}, + lives: {}, + tables: {} +} +``` + +This `ON DELETE` clause can be modified to have some other behaviour besides ignoring when a reference is deleted. + +### ON DELETE REJECT + +`ON DELETE REJECT` will outright make it impossible to delete a record that is referenced from somewhere else. \ No newline at end of file