We can make it a little more complicated now and instead of relating documents by their system ids we can relate a document by a targetField
so if we add a documentId field into the documents table (normally you'd add a unique constraint to the id field but we wont here to demo that the relations will generate indexes properly between parent and child tables)
Then we can add defaults to the field as well to generate a default value either with a caller or a static value. This will set the value on insert and will let you insert to that table without specifying a value for documentId, since it has a default it will default to that. (I havent actually implemented this π’, but it exists in my parser and code gen i just have not made the convex stuff for it)
const Documents = Table('documents', {
userId: v.id('users'),
name: v.string(),
documentId: v.string(),
content: v.string(),
}).constraints((c) => [
c.relation('userId', Users, {
onDelete: 'restrict',
}),
c.default('documentId', () => crypto.randomUUID()),
])
const Attachments = Table('attachments', {
attachmentId: v.string(),
name: v.string(),
url: v.string(),
docId: v.string(),
}).constraints((c) => [
c.unique('attachmentId'),
c.relation('docId', Documents, {
targetField: 'documentId',
onDelete: 'restrict',
}),
c.default('attachmentId', () => crypto.randomUUID()),
])
export default defineSchema(
{
users: Users.toConvexTable(),
documents: Documents.toConvexTable(),
attachments: Attachments.toConvexTable(),
},
{
schemaValidation: true,
}
)