@knorm/relations
Knorm plugin that adds ability to fetch data from multiple tables via SQL joins.
Installation
@knorm/relations has a peer dependency on @knorm/knorm
Usage
Options
| Option | Type | Default | Description |
|---|---|---|---|
| [name] | string | relations | The name of the plugin, allows accessing the plugin instance via Knorm's plugin registry (Knorm.prototype.plugins) |
Features
Loading this plugin adds the following methods to the Query class:
Query.prototype.join- fetches a related model via aJOINstatementQuery.prototype.innerJoin- fetches a related model via anINNER JOINstatementQuery.prototype.leftoin- fetches a related model via aLEFT JOINstatementQuery.prototype.on- specifies which field to join onQuery.prototype.as- specifies what alias to use for the related model in the returned data
Which enables using them as Query options.
One-to-many relations
Similar to adding a foreign key in SQL, one-to-many relations are defined by adding a reference from one field to another:
Once references are defined, joins can then be configured when fetching data:
Query options can also be passed via an object:
info
If as is not specified, it defaults to a camelCase representation of the name
of model being joined.
note
If on is not specified, the join will be done on ALL the fields that have
references to each other for the two models:
One-to-one relations
These are similar to one-to-many joins, but you can configure the join to only
return the first row via the Query.prototype.first Query option:
Many-to-many relations
To create a many-to-many relation, create a model for the many-to-many relational table in your database:
To fetch friend data: