Relations and transactions
Separate foreign keys and relations
Understand the different jobs of database foreign keys and Drizzle relations before using convenient nested queries.
8 minute lesson
Foreign keys and Drizzle relations describe the same connection at different layers. They are not interchangeable.
The foreign key on notes.authorId prevents invalid data in SQLite. A Drizzle relation tells the query API how to fetch an author with notes or a note with its author. Relations do not create constraints or migrations.
This distinction matters when an import script, admin tool, or second service writes outside Drizzle. The database constraint still protects the relationship. An application-only relation does not.
Keep the foreign key even when the relational query API works without it. Only omit database enforcement when you have a concrete distributed-data reason and another integrity plan.
Draw the users-to-notes relationship twice: once as a database constraint and once as a fetch rule. Remove each layer in a disposable branch and record which invalid write or convenient query stops working.
Lesson completed