Defining models
Models in JSORM are pure metadata. They contain field definitions, relations, and database configuration, but no logic or queries.
Basic model
Section titled “Basic model”import { defineModel, t, r } from "@jsorm/core";
export const User = defineModel("users", { db: "main", fields: { id: t.uuid().primary().autoCreate(), name: t.string(100), email: t.string(255).unique(), password: t.string().hidden(), roleId: t.uuid().nullable(), active: t.boolean().default(true), createdAt: t.dateTime().autoCreate(), updatedAt: t.dateTime().autoUpdate(), }, relations: { posts: r.hasMany("post"), role: r.belongsTo("role", { localKey: "roleId" }), },});Fields
Section titled “Fields”Use t.* to define field types. Each type returns a FieldChain with chainable modifiers.
t.string(length?) // FieldChain<"string">t.uuid() // FieldChain<"uuid">t.boolean() // FieldChain<"boolean">t.integer() // FieldChain<"integer">t.decimal(precision?, scale?) // FieldChain<"decimal">t.text() // FieldChain<"text">t.dateTime() // FieldChain<"dateTime">t.json() // FieldChain<"json">t.enum(values) // FieldChain<"enum">Modifiers
Section titled “Modifiers”| Modifier | Description |
|---|---|
.primary() |
Marks as primary key |
.autoCreate() |
Auto-generated on creation |
.autoUpdate() |
Updated on each modification |
.default(value) |
Default value |
.unique() |
Unique constraint |
.nullable() |
Allows null |
.hidden() |
Excluded from SELECT by default |
Example
Section titled “Example”// Primary keyid: t.uuid().primary().autoCreate(),
// Stringsname: t.string(100).unique(),email: t.string(255).unique(),password: t.string(255).hidden(),
// Booleanactive: t.boolean().default(true),
// Numbersage: t.integer(),price: t.decimal(10, 2),
// Text (long content)bio: t.text().nullable(),
// Date/timecreatedAt: t.dateTime().autoCreate(),updatedAt: t.dateTime().autoUpdate(),
// JSON (flexible structure)metadata: t.json().nullable(),
// Enumstatus: t.enum(["active", "inactive", "archived"]),Relations
Section titled “Relations”Use r.* to define relations:
relations: { role: r.belongsTo("role", { localKey: "roleId" }), posts: r.hasMany("post"), profile: r.hasOne("profile"), roles: r.manyToMany("role", { through: "user_roles", localForeignKey: "userId", foreignForeignKey: "roleId", }),}See Relations for more details.
