Can I update a table in Keystone when I add data to another table?
For example: I have a table named Property where I add details of the property. As soon as I enter the data into this Property table, another table, named NewTable, should automatically get populated with the contents.
Is there a way to achieve this?
There are two ways I can see to approach this:
afterOperationhook, which lets you configure an async function that runs after the main operation has finishedUPDATEandINSERTafterOperationHookSee the docs here. There's also a hooks guide with some context on how the hooks system works.
In your case, you'll be adding a function to your
Propertylist config.The
operationargument will tell you what type of operation just occurred ('create','update', or'delete') which may be handy if you also want to reflect changes to Property items or clean up records inNewTablewhen a Property item is deleted.Depending on the type of operation, the data you're interested in will be available in either the
originalItem,itemorresolvedDataarguments:resolvedDatawill contain the values supplied but you'll probably want to referenceitem, it'll also contain generated and defaulted values that were applied, such as the new item'sid. In this caseoriginalItemwill benull.resolvedDatawill be just the data that changed, which should have everything you need to keep the copy in sync. If you want a move compete pictureoriginalItemanditemwill be the entire item before and after the update is applied.originalItemwill be the last version of the item before it was removed from the DB.resolvedDataanditemwill both benull.The
contextargument is a reference to the Keystone context object which includes all the APIs you'll need to write to yourNewTablelist. You probably want the Query API, eg.context.query.NewTable.createOne(),context.query.NewTable.updateOne(), etc.The benefits to using a Keystone hook are:
Database Triggers
Alternatively, I'm pretty sure it's possible to solve this problem at the database level using
UPDATEandINSERTtriggers.This solution is, in a sense, "outside" of Keystone and is database specific. The exact syntax you'll need depends on the DB platform (and version) your project is built on:
You'll need to manually add a migration that creates the relevant database structure and add it to your Keystone
migrationsdir. Once created, Prisma (the DB tooling Keystone uses internally) will ignore the trigger when it's performing its schema comparisons, allowing you to continue using the automatic migrations functionality.Note that, due to how Prisma works, the table with the copy of the data (
NewTablein your example) will need to either be:If you try to manually create and manage a table within the default database schema, Prisma will get confused (producing a
Drift detected: Your database schema is not in sync with your migration historyerror) and prompt you to reset your DB.