In Astro DB, you can establish relationships between tables using foreign keys. However, the current version of Astro DB does not support composite primary keys directly. You can only set one column as the primary key.
Here's an example of how you can set a primary key and a foreign key:
import { defineTable, column } from 'astro:db';
const Author = defineTable({
columns: {
id: column.number({ primaryKey: true }),
name: column.text(),
}
});
const Comment = defineTable({
columns: {
authorId: column.number({ references: () => Author.columns.id }),
body: column.text(),
}
});
In this example, the id column in the Author table is set as the primary key. The authorId column in the Comment table is a foreign key that references the id column in the Author table.
For more complex relationships, you can use the foreignKeys property, which accepts an array of configuration objects that may relate one or more columns between tables:
import { defineTable, column } from 'astro:db';
const Author = defineTable({
columns: {
firstName: column.text(),
lastName: column.text(),
},
});
const Comment = defineTable({
columns: {
authorFirstName: column.text(),
authorLastName: column.text(),
body: column.text(),
},
foreignKeys: [
{
columns: ["authorFirstName", "authorLastName"],
references: () => [Author.columns.firstName, Author.columns.lastName],
},
],
});
In this example, the authorFirstName and authorLastName columns in the Comment table are foreign keys that reference the firstName and lastName columns in the Author table, respectively.