Prerequisites
This recipe is supported on:- PostgreSQL (all versions)
- MySQL versions 8.0.14 and higher
- SQLite (with ParseJSONResultsPlugin)
MySQL 8.0.14+ is required due to the way subqueries use outer references in this recipe. See the MySQL 8.0.14 changelog for details.
JSON data types and functions
PostgreSQL and MySQL have rich JSON support through theirjson data types and functions. The pg and mysql2 node drivers automatically parse returned json columns as JavaScript objects.
Parsing JSON in SQLite
The built-inSqliteDialect and some third-party dialects don’t parse returned JSON columns to objects automatically. If your JSON columns get returned as strings, use the ParseJSONResultsPlugin:
Basic example
Let’s fetch a list of people and nest each person’s pets and mother into the returned objects. Here’s the raw PostgreSQL SQL we want to generate:Using helper functions
Kysely provides helper functions to simplify this pattern:Import built-in helpers
These helpers are included in Kysely. Import them based on your dialect:Type-safe queries with helpers
With these helpers, our query becomes much more readable:Creating reusable relation helpers
For repeated use across your codebase, create dedicated helper functions:Handling nullability
Kysely marks selections as nullable if it can’t determine that the related object always exists. Use$notNull() when you know a relation exists:
Conditional relations
Use$if to select relations conditionally: