Stacks ORM
Key Paths
- Core ORM package:
storage/framework/core/orm/src/
- ORM implementation:
storage/framework/orm/
- Model definitions:
storage/framework/defaults/app/Models/ (50+ models)
- Application models:
app/Models/
- Default model templates:
storage/framework/defaults/app/Models/
- ORM type globals:
storage/framework/types/orm-globals.d.ts
- Attribute types:
storage/framework/types/attributes.ts (240+ attributes)
- Model events:
storage/framework/types/events.ts
Source Files
orm/src/
├── define-model.ts # defineModel() + buildEventHooks() + buildTraitMethods()
├── index.ts # Re-exports orm/src + db + subquery + transaction + types
├── db.ts # Database query builder bridge
├── subquery.ts # Subquery support
├── transaction.ts # transaction(), savepoint(), transactional()
├── model-types.ts # ModelRow<T>, NewModelData<T>, UpdateModelData<T>
├── types.ts # ORM type definitions
├── utils.ts # modelTableName, getRelations, getFillableAttributes, etc.
├── builder.ts # Query builder integration
├── generated/ # Auto-generated model types and table traits
│ ├── types.ts
│ ├── index.ts
│ └── table-traits.ts
└── traits/
├── index.ts # Re-exports all trait creators
├── taggable.ts # createTaggableMethods()
├── categorizable.ts # createCategorizableMethods()
├── commentable.ts # createCommentableMethods()
├── billable.ts # createBillableMethods()
├── likeable.ts # createLikeableMethods()
└── two-factor.ts # createTwoFactorMethods()
defineModel() API (define-model.ts)
Wraps bun-query-builder's createModel() with Stacks-specific enhancements:
- Event dispatching via
traits.observe (emits {model}:created, {model}:updated, {model}:deleted via @stacksjs/events)
- Trait methods (billable, taggable, categorizable, commentable, likeable, 2FA)
- Raw definition access for generators (
getDefinition(), _isStacksModel)
import { defineModel } from '@stacksjs/orm'
export default defineModel({
name: 'Product',
table: 'products',
primaryKey: 'id', // default: 'id'
autoIncrement: true, // default: true
traits: {
useUuid: true, // adds uuid column
useTimestamps: true, // adds created_at, updated_at
useAuth: { usePasskey: true }, // adds auth columns + passkey support
useSocials: ['github'], // social login providers
useSearch: { // search engine indexing
displayable: ['name', 'email'],
searchable: ['name', 'email'],
sortable: ['name', 'created_at'],
filterable: ['status']
},
useSeeder: { count: 10 }, // or just `true` (defaults to 10)
useApi: {
uri: 'products',
routes: ['index', 'store', 'show', 'update', 'destroy']
},
categorizable: true, // adds category relations via categorizable table
taggable: true, // adds tag relations via taggable table
commentables: true, // adds comment relations (NOTE: plural 's' in key)
billable: true, // adds Stripe integration methods
likeable: true, // or { table?: string, foreignKey?: string }
observe: true, // emit model events (true = all, or array: ['create','update','delete'])
},
// Relationships
hasOne: ['Subscriber'],
hasMany: ['Post', 'Order'],
belongsTo: ['User', 'Category'],
belongsToMany: ['Tag'],
hasOneThrough: ['Profile'],
morphOne: 'Image', // or { model, morphName?, type?, id? }
indexes: [
{ name: 'idx_email', columns: ['email'] },
{ name: 'idx_composite', columns: ['email', 'name'] }
],
attributes: {
name: {
order: 1,
fillable: true,
required: true,
unique: false,
validation: {
rule: schema.string().maxLength(100),
message: { maxLength: 'Name is too long' }
},
factory: (faker) => faker.lorem.word()
},
price: {
fillable: true,
required: true,
validation: { rule: schema.number().min(1) },
factory: (faker) => faker.datatype.number({ min: 100, max: 10000 })
},
status: {
fillable: true,
default: 'draft',
validation: { rule: schema.enum(['draft', 'published', 'archived']) }
},
password: {
hidden: true, // excluded from JSON serialization
guarded: true, // not mass-assignable
}
},
// Computed properties (accessors)
get: {
fullName: (attrs) => `${attrs.first_name} ${attrs.last_name}`,
formattedPrice: (attrs) => `$${(attrs.price / 100).toFixed(2)}`
},
// Mutators (setters)
set: {
email: (attrs) => attrs.email?.toLowerCase()
},
// Model hooks (lifecycle callbacks)
hooks: {
afterCreate: (model) => { /* ... */ },
afterUpdate: (model) => { /* ... */ },
afterDelete: (model) => { /* ... */ },
},
dashboard: { highlight: true } // highlight in admin dashboard
} as const)
How defineModel() Works Internally
buildEventHooks(definition) -- if traits.observe is truthy, creates afterCreate/afterUpdate/afterDelete hooks that lazy-import @stacksjs/events and call dispatch()
- Merges event hooks with any user-defined hooks
- Calls
createModel(defWithHooks) from bun-query-builder (provides typed query methods)
buildTraitMethods(definition) -- checks each trait flag and creates method objects
- Returns
Object.assign(baseModel, traitMethods, definition) + getDefinition() + _isStacksModel
Transactions (transaction.ts)
import { transaction, savepoint, transactional } from '@stacksjs/orm'
// Basic transaction -- auto-commit on success, auto-rollback on error
const result = await transaction(async (tx) => {
await tx.insertInto('users').values({ name: 'John' }).execute()
await tx.insertInto('profiles').values({ user_id: 1 }).execute()
return 'success'
})
// With options
await transaction(callback, {
retries: 3,
isolation: 'serializable', // 'read committed' | 'repeatable read' | 'serializable'
readOnly: false,
onRollback: (error) => console.error(error),
afterRollback: () => { /* cleanup */ }
})
// Savepoints (nested transactions)
await transaction(async (tx) => {
await tx.insertInto('users').values({ name: 'Bob' }).execute()
await savepoint(async (sp) => {
await sp.insertInto('logs').values({ action: 'created' }).execute()
// If this fails, only this savepoint rolls back
})
})
// Decorator-style -- wraps function to auto-run in transaction
const createUser = transactional(async (tx, name: string, email: string) => {
const user = await tx.insertInto('users').values({ name }).returningAll().executeTakeFirst()
await tx.insertInto('profiles').values({ user_id: user.id }).execute()
return user
})
await createUser('Alice', 'alice@example.com') // auto-wrapped
Both transaction() and savepoint() delegate to db.transaction() and db.savepoint() from @stacksjs/database.
Trait Methods (traits/)
Taggable (when traits.taggable: true)
Uses taggable table with polymorphic taggable_type + taggable_id columns.
Model._taggable.tags(id: number): Promise<any[]>
Model._taggable.tagCount(id: number): Promise<number> -- uses count(*)
Model._taggable.addTag(id, { name, description? }): Promise<any> -- auto-generates slug
Model._taggable.activeTags(id): Promise<any[]> -- filters is_active = true
Model._taggable.inactiveTags(id): Promise<any[]> -- filters is_active = false
Model._taggable.removeTag(id, tagId): Promise<void>
Categorizable (when traits.categorizable: true)
Uses categorizable + categorizable_models pivot table.
Model._categorizable.categories(id): Promise<any[]> -- joins through pivot
Model._categorizable.categoryCount(id): Promise<number>
Model._categorizable.addCategory(id, { name, description? }): Promise<any> -- creates category if not exists, then links
Model._categorizable.activeCategories(id): Promise<any[]>
Model._categorizable.inactiveCategories(id): Promise<any[]>
Model._categorizable.removeCategory(id, categoryId): Promise<void> -- removes pivot link
Commentable (when traits.commentables: true)
Uses comments table with commentables_id + commentables_type columns.
Model._commentable.comments(id): Promise<any[]>
Model._commentable.commentCount(id): Promise<number>
Model._commentable.addComment(id, { title, body }): Promise<any> -- status defaults to 'pending'
Model._commentable.approvedComments(id): Promise<any[]> -- status = 'approved'
Model._commentable.pendingComments(id): Promise<any[]> -- status = 'pending'
Model._commentable.rejectedComments(id): Promise<any[]> -- status = 'rejected'
Likeable (when traits.likeable: true or { table?, foreignKey? })
Table defaults to {tableName}_likes, FK defaults to {singular}_id.
Model._likeable.likes(id): Promise<any[]>
Model._likeable.likeCount(id): Promise<number>
Model._likeable.like(id, userId): Promise<any>
Model._likeable.unlike(id, userId): Promise<void>
Model._likeable.isLiked(id, userId): Promise<boolean>
Billable (when traits.billable: true) -- Stripe integration
All methods lazy-import @stacksjs/payments.
createStripeUser(model, options), updateStripeUser(model, options), deleteStripeUser(model)
createOrGetStripeUser(model, options), retrieveStripeUser(model)
defaultPaymentMethod(model), setDefaultPaymentMethod(model, pmId), addPaymentMethod(model, paymentMethodId), paymentMethods(model, cardType?)
newSubscription(model, type, lookupKey, options) -- returns { subscription, paymentIntent }
updateSubscription(model, type, lookupKey, options), cancelSubscription(model, providerId, options)
activeSubscription(model) -- queries subscriptions table for provider_status = 'active', then retrieves from Stripe
checkout(model, priceIds[], options) -- supports enableTax, allowPromotions options
createSetupIntent(model, options), subscriptionHistory(model), transactionHistory(model)
Two-Factor Auth (when traits.useAuth.useTwoFactor: true)
Model._twoFactor.generateTwoFactorForModel(model) -- generates secret, calls model.update()
Model._twoFactor.verifyTwoFactorCode(model, code): Promise<boolean>
Auto-Generated System Fields
id -- primary key (auto-increment)
created_at, updated_at -- when useTimestamps: true
uuid -- when useUuid: true
deleted_at -- when soft deletes enabled
stripe_id -- when billable: true
two_factor_secret, public_key -- when useAuth: { usePasskey: true }
Naming Conventions
- Model: PascalCase (
ProductVariant)
- Table: snake_case plural (
product_variants)
- Column: snake_case (
first_name)
- Foreign key:
{singular_model}_id (user_id)
- Pivot table: alphabetical sort of both table names (
category_product)
ORM Utility Types (model-types.ts)
type Def<T> = T extends { getDefinition: () => infer D } ? D : never
type BelongsToForeignKeys<TDef> // extracts { modelname_id: number } from belongsTo array
type ModelRow<T> = ModelAttributes<Def<T>> & BelongsToForeignKeys<Def<T>>
type NewModelData<T> = Partial<InferModelAttributes<Def<T>> & BelongsToForeignKeys<Def<T>>>
type UpdateModelData<T> = Partial<InferModelAttributes<Def<T>> & BelongsToForeignKeys<Def<T>>>
ORM Utility Functions (utils.ts)
modelTableName(model: Model | string): Promise<string> -- uses model.table or converts model.name to snake_case plural
getModelName(model, modelPath): string -- from definition or filename
getTableName(model, modelPath): TableNames -- from definition or snake_case plural of name
getPivotTableName(modelA, modelB): string -- alphabetical sort + join with _
getRelations(model, name): Promise<RelationConfig[]> -- processes hasOne, hasMany, belongsTo, hasOneThrough, belongsToMany, morphOne
getHiddenAttributes(attrs): string[] -- filters for hidden: true
getGuardedAttributes(model): string[] -- filters for guarded: true, returns snake_case
getFillableAttributes(model, relations): string[] -- filters for fillable: true, adds FK columns, stripe_id, uuid, etc.
extractFields(model, file): Promise<ModelElement[]> -- parses model file for field metadata
findCoreModel(name): string -- searches storage/framework/defaults/app/Models/ recursively
findUserModel(name): string -- searches app/Models/
fetchOtherModelRelations(modelName?): Promise<RelationConfig[]> -- scans all models for relations pointing to this model
formatDate(date): string -- ISO format YYYY-MM-DD HH:MM:SS
Relationship Processing (utils.ts)
Each relationship type is processed into a RelationConfig object:
- hasOne / hasMany: FK =
{parent_snake}_id, model key = {related_snake}_id
- belongsTo: FK is empty string (set on the owning model's side), supports custom
foreignKey
- belongsToMany: the legacy array form auto-creates a conventional pivot and supports
pivotTable, firstForeignKey, and secondForeignKey; the named object form supports table, foreignKey, relatedKey, and pivot metadata (columns, timestamps, uniques)
- hasOneThrough: includes
throughModel and throughForeignKey
- morphOne: uses
{modelName}able pattern, generates _type and _id columns
Named many-to-many relations are callable on model instances. Use their native
relation builder for pivot writes:
const post = await Post.find(id)
await post.categories().sync(categoryIds)
await post.tags().attach(tagId)
await post.tags().detach()
Declaring custom pivot columns in the model is required when those columns have
defaults that attach() and sync() must write. pivot.timestamps: true
causes both timestamps to be generated and maintained.
Model Events (when traits.observe: true)
observe: true emits all three events. observe: ['create', 'update'] emits only those.
'{modelname}:created' -- via afterCreate hook, lazy-imports @stacksjs/events
'{modelname}:updated' -- via afterUpdate hook
'{modelname}:deleted' -- via afterDelete hook
If @stacksjs/events is not available (browser, tests), errors are caught and silently ignored.
Stub Types in index.ts
The ORM exports stub types for commonly used models to keep typecheck green before code generation:
UserModel, NewUser, User (class stub with static where, find, create, all)
Job, FailedJob (query stubs)
PaymentMethod (CRUD stubs)
CategorizableTable, CategorizableModelsTable, CommentablesTable, TaggableTable
All 50+ Framework Models
Content: Author, Page, Post, Comment, Tag, Category
Users: User, Customer, Driver, Subscriber, SubscriberEmail
Commerce: Product, ProductVariant, ProductUnit, Cart, CartItem, Order, OrderItem, Coupon, GiftCard, Manufacturer, Review, LicenseKey, DigitalDelivery, WaitlistProduct, WaitlistRestaurant
Payments: Payment, PaymentMethod, PaymentProduct, PaymentTransaction, Subscription, Transaction, Receipt
Shipping: ShippingMethod, ShippingRate, ShippingZone, DeliveryRoute
Loyalty: LoyaltyPoint, LoyaltyReward, TaxRate
System: Job, FailedJob, Error, Log, Notification, Activity, Request, Websocket, PrintDevice
Marketing: Campaign, EmailList, SocialPost
CLI Commands
buddy make:migration -- create migration for model changes
buddy generate:migrations -- generate migrations from model diffs
buddy migrate -- run pending migrations
Gotchas
- Models work directly via the dynamic ORM — no code generation step needed
defineModel() calls createModel() from bun-query-builder at runtime, providing all typed query methods immediately
- Two ORM locations:
storage/framework/core/orm/ (package) and storage/framework/orm/ (implementation)
- Factories use
@stacksjs/faker -- each attribute can have a factory function
- The
hidden attribute flag excludes fields from JSON serialization (e.g., passwords)
- The
guarded flag prevents mass assignment
- The
fillable flag explicitly allows mass assignment
- Pivot tables for belongsToMany are auto-created using alphabetical naming of both table names
- Model events are only emitted when
observe: true (or array) trait is set
- The trait key for commentable is
commentables (with 's'), not commentable
- Trait methods are accessed via underscore-prefixed properties:
_taggable, _categorizable, _commentable, _billable, _likeable, _twoFactor
- The
useAuth.useTwoFactor check (not usePasskey) determines if two-factor methods are added
defineModel() calls createModel() from bun-query-builder which returns the typed query builder interface at runtime
- Model file loading uses
findUserModel() (app/Models/) with fallback to findCoreModel() (storage/framework/defaults/app/Models/)
1---2name: stacks-orm-43description: Use when working with the Stacks ORM — defining models with defineModel(), model relationships (hasOne, hasMany, belongsTo, belongsToMany, morphOne, hasManyThrough), attributes, traits, factories, computed properties, query building, transactions, or the 50+ built-in models. Covers @stacksjs/orm, storage/framework/orm/, and storage/framework/defaults/app/Models/.4license: MIT5compatibility: Bun >= 1.3.0, TypeScript, SQLite >= 3.47.26allowed-tools: Read Edit Write Bash Grep Glob7metadata:8 source: https://skillmd.com/skills/stacksjs/stacks-orm-49---1011# Stacks ORM1213## Key Paths14- Core ORM package: `storage/framework/core/orm/src/`15- ORM implementation: `storage/framework/orm/`16- Model definitions: `storage/framework/defaults/app/Models/` (50+ models)17- Application models: `app/Models/`18- Default model templates: `storage/framework/defaults/app/Models/`19- ORM type globals: `storage/framework/types/orm-globals.d.ts`20- Attribute types: `storage/framework/types/attributes.ts` (240+ attributes)21- Model events: `storage/framework/types/events.ts`2223## Source Files24```25orm/src/26├── define-model.ts # defineModel() + buildEventHooks() + buildTraitMethods()27├── index.ts # Re-exports orm/src + db + subquery + transaction + types28├── db.ts # Database query builder bridge29├── subquery.ts # Subquery support30├── transaction.ts # transaction(), savepoint(), transactional()31├── model-types.ts # ModelRow<T>, NewModelData<T>, UpdateModelData<T>32├── types.ts # ORM type definitions33├── utils.ts # modelTableName, getRelations, getFillableAttributes, etc.34├── builder.ts # Query builder integration35├── generated/ # Auto-generated model types and table traits36│ ├── types.ts37│ ├── index.ts38│ └── table-traits.ts39└── traits/40 ├── index.ts # Re-exports all trait creators41 ├── taggable.ts # createTaggableMethods()42 ├── categorizable.ts # createCategorizableMethods()43 ├── commentable.ts # createCommentableMethods()44 ├── billable.ts # createBillableMethods()45 ├── likeable.ts # createLikeableMethods()46 └── two-factor.ts # createTwoFactorMethods()47```4849## defineModel() API (define-model.ts)5051Wraps bun-query-builder's `createModel()` with Stacks-specific enhancements:52- Event dispatching via `traits.observe` (emits `{model}:created`, `{model}:updated`, `{model}:deleted` via `@stacksjs/events`)53- Trait methods (billable, taggable, categorizable, commentable, likeable, 2FA)54- Raw definition access for generators (`getDefinition()`, `_isStacksModel`)5556```typescript57import { defineModel } from '@stacksjs/orm'5859export default defineModel({60 name: 'Product',61 table: 'products',62 primaryKey: 'id', // default: 'id'63 autoIncrement: true, // default: true6465 traits: {66 useUuid: true, // adds uuid column67 useTimestamps: true, // adds created_at, updated_at68 useAuth: { usePasskey: true }, // adds auth columns + passkey support69 useSocials: ['github'], // social login providers70 useSearch: { // search engine indexing71 displayable: ['name', 'email'],72 searchable: ['name', 'email'],73 sortable: ['name', 'created_at'],74 filterable: ['status']75 },76 useSeeder: { count: 10 }, // or just `true` (defaults to 10)77 useApi: {78 uri: 'products',79 routes: ['index', 'store', 'show', 'update', 'destroy']80 },81 categorizable: true, // adds category relations via categorizable table82 taggable: true, // adds tag relations via taggable table83 commentables: true, // adds comment relations (NOTE: plural 's' in key)84 billable: true, // adds Stripe integration methods85 likeable: true, // or { table?: string, foreignKey?: string }86 observe: true, // emit model events (true = all, or array: ['create','update','delete'])87 },8889 // Relationships90 hasOne: ['Subscriber'],91 hasMany: ['Post', 'Order'],92 belongsTo: ['User', 'Category'],93 belongsToMany: ['Tag'],94 hasOneThrough: ['Profile'],95 morphOne: 'Image', // or { model, morphName?, type?, id? }9697 indexes: [98 { name: 'idx_email', columns: ['email'] },99 { name: 'idx_composite', columns: ['email', 'name'] }100 ],101102 attributes: {103 name: {104 order: 1,105 fillable: true,106 required: true,107 unique: false,108 validation: {109 rule: schema.string().maxLength(100),110 message: { maxLength: 'Name is too long' }111 },112 factory: (faker) => faker.lorem.word()113 },114 price: {115 fillable: true,116 required: true,117 validation: { rule: schema.number().min(1) },118 factory: (faker) => faker.datatype.number({ min: 100, max: 10000 })119 },120 status: {121 fillable: true,122 default: 'draft',123 validation: { rule: schema.enum(['draft', 'published', 'archived']) }124 },125 password: {126 hidden: true, // excluded from JSON serialization127 guarded: true, // not mass-assignable128 }129 },130131 // Computed properties (accessors)132 get: {133 fullName: (attrs) => `${attrs.first_name} ${attrs.last_name}`,134 formattedPrice: (attrs) => `$${(attrs.price / 100).toFixed(2)}`135 },136137 // Mutators (setters)138 set: {139 email: (attrs) => attrs.email?.toLowerCase()140 },141142 // Model hooks (lifecycle callbacks)143 hooks: {144 afterCreate: (model) => { /* ... */ },145 afterUpdate: (model) => { /* ... */ },146 afterDelete: (model) => { /* ... */ },147 },148149 dashboard: { highlight: true } // highlight in admin dashboard150} as const)151```152153### How defineModel() Works Internally1541. `buildEventHooks(definition)` -- if `traits.observe` is truthy, creates `afterCreate`/`afterUpdate`/`afterDelete` hooks that lazy-import `@stacksjs/events` and call `dispatch()`1552. Merges event hooks with any user-defined hooks1563. Calls `createModel(defWithHooks)` from bun-query-builder (provides typed query methods)1574. `buildTraitMethods(definition)` -- checks each trait flag and creates method objects1585. Returns `Object.assign(baseModel, traitMethods, definition)` + `getDefinition()` + `_isStacksModel`159160## Transactions (transaction.ts)161162```typescript163import { transaction, savepoint, transactional } from '@stacksjs/orm'164165// Basic transaction -- auto-commit on success, auto-rollback on error166const result = await transaction(async (tx) => {167 await tx.insertInto('users').values({ name: 'John' }).execute()168 await tx.insertInto('profiles').values({ user_id: 1 }).execute()169 return 'success'170})171172// With options173await transaction(callback, {174 retries: 3,175 isolation: 'serializable', // 'read committed' | 'repeatable read' | 'serializable'176 readOnly: false,177 onRollback: (error) => console.error(error),178 afterRollback: () => { /* cleanup */ }179})180181// Savepoints (nested transactions)182await transaction(async (tx) => {183 await tx.insertInto('users').values({ name: 'Bob' }).execute()184 await savepoint(async (sp) => {185 await sp.insertInto('logs').values({ action: 'created' }).execute()186 // If this fails, only this savepoint rolls back187 })188})189190// Decorator-style -- wraps function to auto-run in transaction191const createUser = transactional(async (tx, name: string, email: string) => {192 const user = await tx.insertInto('users').values({ name }).returningAll().executeTakeFirst()193 await tx.insertInto('profiles').values({ user_id: user.id }).execute()194 return user195})196await createUser('Alice', 'alice@example.com') // auto-wrapped197```198199Both `transaction()` and `savepoint()` delegate to `db.transaction()` and `db.savepoint()` from `@stacksjs/database`.200201## Trait Methods (traits/)202203### Taggable (when `traits.taggable: true`)204Uses `taggable` table with polymorphic `taggable_type` + `taggable_id` columns.205- `Model._taggable.tags(id: number): Promise<any[]>`206- `Model._taggable.tagCount(id: number): Promise<number>` -- uses `count(*)`207- `Model._taggable.addTag(id, { name, description? }): Promise<any>` -- auto-generates slug208- `Model._taggable.activeTags(id): Promise<any[]>` -- filters `is_active = true`209- `Model._taggable.inactiveTags(id): Promise<any[]>` -- filters `is_active = false`210- `Model._taggable.removeTag(id, tagId): Promise<void>`211212### Categorizable (when `traits.categorizable: true`)213Uses `categorizable` + `categorizable_models` pivot table.214- `Model._categorizable.categories(id): Promise<any[]>` -- joins through pivot215- `Model._categorizable.categoryCount(id): Promise<number>`216- `Model._categorizable.addCategory(id, { name, description? }): Promise<any>` -- creates category if not exists, then links217- `Model._categorizable.activeCategories(id): Promise<any[]>`218- `Model._categorizable.inactiveCategories(id): Promise<any[]>`219- `Model._categorizable.removeCategory(id, categoryId): Promise<void>` -- removes pivot link220221### Commentable (when `traits.commentables: true`)222Uses `comments` table with `commentables_id` + `commentables_type` columns.223- `Model._commentable.comments(id): Promise<any[]>`224- `Model._commentable.commentCount(id): Promise<number>`225- `Model._commentable.addComment(id, { title, body }): Promise<any>` -- status defaults to `'pending'`226- `Model._commentable.approvedComments(id): Promise<any[]>` -- status = `'approved'`227- `Model._commentable.pendingComments(id): Promise<any[]>` -- status = `'pending'`228- `Model._commentable.rejectedComments(id): Promise<any[]>` -- status = `'rejected'`229230### Likeable (when `traits.likeable: true` or `{ table?, foreignKey? }`)231Table defaults to `{tableName}_likes`, FK defaults to `{singular}_id`.232- `Model._likeable.likes(id): Promise<any[]>`233- `Model._likeable.likeCount(id): Promise<number>`234- `Model._likeable.like(id, userId): Promise<any>`235- `Model._likeable.unlike(id, userId): Promise<void>`236- `Model._likeable.isLiked(id, userId): Promise<boolean>`237238### Billable (when `traits.billable: true`) -- Stripe integration239All methods lazy-import `@stacksjs/payments`.240- `createStripeUser(model, options)`, `updateStripeUser(model, options)`, `deleteStripeUser(model)`241- `createOrGetStripeUser(model, options)`, `retrieveStripeUser(model)`242- `defaultPaymentMethod(model)`, `setDefaultPaymentMethod(model, pmId)`, `addPaymentMethod(model, paymentMethodId)`, `paymentMethods(model, cardType?)`243- `newSubscription(model, type, lookupKey, options)` -- returns `{ subscription, paymentIntent }`244- `updateSubscription(model, type, lookupKey, options)`, `cancelSubscription(model, providerId, options)`245- `activeSubscription(model)` -- queries `subscriptions` table for `provider_status = 'active'`, then retrieves from Stripe246- `checkout(model, priceIds[], options)` -- supports `enableTax`, `allowPromotions` options247- `createSetupIntent(model, options)`, `subscriptionHistory(model)`, `transactionHistory(model)`248249### Two-Factor Auth (when `traits.useAuth.useTwoFactor: true`)250- `Model._twoFactor.generateTwoFactorForModel(model)` -- generates secret, calls `model.update()`251- `Model._twoFactor.verifyTwoFactorCode(model, code): Promise<boolean>`252253## Auto-Generated System Fields254- `id` -- primary key (auto-increment)255- `created_at`, `updated_at` -- when `useTimestamps: true`256- `uuid` -- when `useUuid: true`257- `deleted_at` -- when soft deletes enabled258- `stripe_id` -- when `billable: true`259- `two_factor_secret`, `public_key` -- when `useAuth: { usePasskey: true }`260261## Naming Conventions262- Model: PascalCase (`ProductVariant`)263- Table: snake_case plural (`product_variants`)264- Column: snake_case (`first_name`)265- Foreign key: `{singular_model}_id` (`user_id`)266- Pivot table: alphabetical sort of both table names (`category_product`)267268## ORM Utility Types (model-types.ts)269```typescript270type Def<T> = T extends { getDefinition: () => infer D } ? D : never271type BelongsToForeignKeys<TDef> // extracts { modelname_id: number } from belongsTo array272type ModelRow<T> = ModelAttributes<Def<T>> & BelongsToForeignKeys<Def<T>>273type NewModelData<T> = Partial<InferModelAttributes<Def<T>> & BelongsToForeignKeys<Def<T>>>274type UpdateModelData<T> = Partial<InferModelAttributes<Def<T>> & BelongsToForeignKeys<Def<T>>>275```276277## ORM Utility Functions (utils.ts)278- `modelTableName(model: Model | string): Promise<string>` -- uses `model.table` or converts `model.name` to snake_case plural279- `getModelName(model, modelPath): string` -- from definition or filename280- `getTableName(model, modelPath): TableNames` -- from definition or snake_case plural of name281- `getPivotTableName(modelA, modelB): string` -- alphabetical sort + join with `_`282- `getRelations(model, name): Promise<RelationConfig[]>` -- processes hasOne, hasMany, belongsTo, hasOneThrough, belongsToMany, morphOne283- `getHiddenAttributes(attrs): string[]` -- filters for `hidden: true`284- `getGuardedAttributes(model): string[]` -- filters for `guarded: true`, returns snake_case285- `getFillableAttributes(model, relations): string[]` -- filters for `fillable: true`, adds FK columns, stripe_id, uuid, etc.286- `extractFields(model, file): Promise<ModelElement[]>` -- parses model file for field metadata287- `findCoreModel(name): string` -- searches `storage/framework/defaults/app/Models/` recursively288- `findUserModel(name): string` -- searches `app/Models/`289- `fetchOtherModelRelations(modelName?): Promise<RelationConfig[]>` -- scans all models for relations pointing to this model290- `formatDate(date): string` -- ISO format `YYYY-MM-DD HH:MM:SS`291292## Relationship Processing (utils.ts)293Each relationship type is processed into a `RelationConfig` object:294- **hasOne / hasMany**: FK = `{parent_snake}_id`, model key = `{related_snake}_id`295- **belongsTo**: FK is empty string (set on the owning model's side), supports custom `foreignKey`296- **belongsToMany**: the legacy array form auto-creates a conventional pivot and supports `pivotTable`, `firstForeignKey`, and `secondForeignKey`; the named object form supports `table`, `foreignKey`, `relatedKey`, and `pivot` metadata (`columns`, `timestamps`, `uniques`)297- **hasOneThrough**: includes `throughModel` and `throughForeignKey`298- **morphOne**: uses `{modelName}able` pattern, generates `_type` and `_id` columns299300Named many-to-many relations are callable on model instances. Use their native301relation builder for pivot writes:302303```ts304const post = await Post.find(id)305await post.categories().sync(categoryIds)306await post.tags().attach(tagId)307await post.tags().detach()308```309310Declaring custom pivot columns in the model is required when those columns have311defaults that `attach()` and `sync()` must write. `pivot.timestamps: true`312causes both timestamps to be generated and maintained.313314## Model Events (when `traits.observe: true`)315`observe: true` emits all three events. `observe: ['create', 'update']` emits only those.316- `'{modelname}:created'` -- via `afterCreate` hook, lazy-imports `@stacksjs/events`317- `'{modelname}:updated'` -- via `afterUpdate` hook318- `'{modelname}:deleted'` -- via `afterDelete` hook319320If `@stacksjs/events` is not available (browser, tests), errors are caught and silently ignored.321322## Stub Types in index.ts323The ORM exports stub types for commonly used models to keep typecheck green before code generation:324- `UserModel`, `NewUser`, `User` (class stub with static `where`, `find`, `create`, `all`)325- `Job`, `FailedJob` (query stubs)326- `PaymentMethod` (CRUD stubs)327- `CategorizableTable`, `CategorizableModelsTable`, `CommentablesTable`, `TaggableTable`328329## All 50+ Framework Models330Content: Author, Page, Post, Comment, Tag, Category331Users: User, Customer, Driver, Subscriber, SubscriberEmail332Commerce: Product, ProductVariant, ProductUnit, Cart, CartItem, Order, OrderItem, Coupon, GiftCard, Manufacturer, Review, LicenseKey, DigitalDelivery, WaitlistProduct, WaitlistRestaurant333Payments: Payment, PaymentMethod, PaymentProduct, PaymentTransaction, Subscription, Transaction, Receipt334Shipping: ShippingMethod, ShippingRate, ShippingZone, DeliveryRoute335Loyalty: LoyaltyPoint, LoyaltyReward, TaxRate336System: Job, FailedJob, Error, Log, Notification, Activity, Request, Websocket, PrintDevice337Marketing: Campaign, EmailList, SocialPost338339## CLI Commands340- `buddy make:migration` -- create migration for model changes341- `buddy generate:migrations` -- generate migrations from model diffs342- `buddy migrate` -- run pending migrations343344## Gotchas345- Models work directly via the dynamic ORM — no code generation step needed346- `defineModel()` calls `createModel()` from bun-query-builder at runtime, providing all typed query methods immediately347- Two ORM locations: `storage/framework/core/orm/` (package) and `storage/framework/orm/` (implementation)348- Factories use `@stacksjs/faker` -- each attribute can have a `factory` function349- The `hidden` attribute flag excludes fields from JSON serialization (e.g., passwords)350- The `guarded` flag prevents mass assignment351- The `fillable` flag explicitly allows mass assignment352- Pivot tables for belongsToMany are auto-created using alphabetical naming of both table names353- Model events are only emitted when `observe: true` (or array) trait is set354- The trait key for commentable is `commentables` (with 's'), not `commentable`355- Trait methods are accessed via underscore-prefixed properties: `_taggable`, `_categorizable`, `_commentable`, `_billable`, `_likeable`, `_twoFactor`356- The `useAuth.useTwoFactor` check (not `usePasskey`) determines if two-factor methods are added357- `defineModel()` calls `createModel()` from bun-query-builder which returns the typed query builder interface at runtime358- Model file loading uses `findUserModel()` (app/Models/) with fallback to `findCoreModel()` (storage/framework/defaults/app/Models/)