Stacks Models
Key Paths
- Your models:
app/Models/ (create it; it does not exist in a fresh project)
- Built-in models:
storage/framework/defaults/app/Models/ (62 files, grouped
into commerce/, Content/, realtime/ and a flat top level)
ModelOptions / Attribute types: storage/framework/core/types/src/model.ts
- Attribute presets:
storage/framework/types/attributes.ts
To customize a built-in model, create the same filename under app/Models/ -
app/Models/User.ts wins over the default. buddy publish:model User copies the
default across as a starting point.
Writing a model
Everything - schema, validation, factory, relationships, behavior - is declared
in one defineModel() call. Migrations are derived from this; you do not write
the SQL.
// app/Models/Product.ts
import { defineModel } from '@stacksjs/orm'
import { schema } from '@stacksjs/validation'
export default defineModel({
name: 'Product', // defaults to the file name
table: 'products', // defaults to lowercase plural of `name`
primaryKey: 'id', // default
autoIncrement: true, // default
traits: {
useUuid: true,
useTimestamps: true,
useApi: { uri: 'products', routes: ['index', 'store', 'show', 'update', 'destroy'] },
useSearch: { searchable: ['name'], filterable: ['status'] },
observe: true,
},
belongsTo: ['Category'],
hasMany: ['Review'],
attributes: {
name: {
required: true,
fillable: true,
order: 1,
validation: {
rule: schema.string().min(3).max(100),
message: { max: 'Name must have a maximum of 100 characters' },
},
factory: faker => faker.commerce.productName(),
},
status: {
required: true,
fillable: true,
default: 'draft',
validation: { rule: schema.enum(['draft', 'published', 'archived']) },
factory: faker => faker.helpers.arrayElement(['draft', 'published', 'archived']),
},
},
} as const)
as const is what the built-in models use - it narrows literal types so the
generated model types stay precise.
Attribute fields
validation.rule is the only required key on an attribute.
| Field |
Effect |
required |
Value required; emits a NOT NULL column |
nullable |
Explicit nullability override |
default |
Column default (string | number | boolean | Date) |
unique |
Unique constraint |
type |
Force the column type instead of inferring from the rule |
order |
Column order in the table and in dashboard forms |
fillable |
Allow mass assignment |
guarded |
Block mass assignment |
hidden |
Exclude from JSON serialization (passwords, tokens) |
foreignKey |
Disable, infer, or configure the FK constraint |
factory |
(faker) => value, used by seeders and tests |
validation |
{ rule, message? } - rule from schema, message keyed by rule name |
Traits
| Trait |
What it adds |
useUuid |
UUID column alongside the primary key |
useTimestamps (alias timestampable) |
created_at / updated_at. On by default |
useSoftDeletes (alias softDeletable) |
deleted_at plus soft-delete query scopes |
useAuth (alias authenticatable) |
Auth columns; { usePasskey: true } adds passkeys. Also confers morphMany: { tokenable: 'PersonalAccessToken' }, so any authenticatable model can hold API tokens |
useApi |
Generates REST actions and routes: { uri, routes, middleware? } |
useSearch (alias searchable) |
Search-engine indexing: { displayable, searchable, sortable, filterable } |
useSocials |
OAuth identities, e.g. ['github'] |
useActivityLog |
Writes an activities feed row per change: { logOnly } / { include } / { exclude } pick the attributes |
useAudit |
Writes a model_audits row per change with an old/new diff |
observe |
Emits {model}:created / :updated / :deleted events |
billable |
Stripe methods (checkout(), activeSubscription(), ...) |
taggable / categorizable / commentable / likeable |
Pivot tables and their relation methods |
Also at the top level: indexes: [{ name, columns, unique?, where? }] for
composite and partial-unique indexes, and dashboard: { highlight: true } to
feature the model in the admin UI.
useApi is an API capability, not a dashboard-view generator. Its generated
routes are registered from the merged model registry. Framework defaults are
loaded first, then recursive app/Models/ definitions override matching model
names. Protect non-public resources at the model:
useApi: {
uri: 'mail-preferences',
routes: ['index', 'store', 'show', 'update', 'destroy'],
middleware: ['auth'],
}
Dashboard-specific endpoints may still use scoped Actions when their transport
shape, authorization boundary, or aggregation differs from generic CRUD. Do
not expose a sensitive model through unguarded generated routes just because a
separate dashboard endpoint is protected.
Generated store and update routes accept both spellings of every fillable
attribute and each foreign key implied by belongsTo. Declaring Product as a
belongs-to relation therefore accepts productId or product_id without
duplicating that relationship column as an attribute.
Relationships
hasOne, hasMany, belongsTo, belongsToMany, hasOneThrough,
hasManyThrough, morphOne, morphMany, morphTo, morphToMany,
morphedByMany. Each takes an array of model names, or an object form when you
need to name the foreign key.
The object form is also where a belongsTo says what happens to its row when
the row it points at is deleted:
belongsTo: [
{ model: 'Repository', onDelete: 'cascade' },
{ model: 'User', foreignKey: 'author_id', onDelete: 'set null' },
],
'cascade' | 'set null' | 'restrict' | 'no action', enforced by the database
on the foreign key. Left off, the default applies: the delete is refused while
a child still points at the row.
Worth declaring rather than deleting children in application code. The order
has to be right in every place that deletes, forever, and the place that misses
one leaves rows nothing can reach - while the database applies the rule to
deletes the application never made: a manual DELETE, a restore, another
service sharing the schema. Not for a polymorphic pair (commentable_id
beside commentable_type): those carry no foreign key at all, because a
constraint would name one table and reject every row pointing at another.
Use the named object form for a many-to-many relation that owns its pivot
schema. It keeps the relation accessor, migration, pivot defaults, timestamps,
and uniqueness in the model definition:
belongsToMany: {
tags: {
model: 'Tag',
table: 'taggable_models',
foreignKey: 'taggable_id',
relatedKey: 'tag_id',
pivot: {
columns: {
taggable_type: { default: 'posts' },
},
timestamps: true,
uniques: [['tag_id', 'taggable_id', 'taggable_type']],
},
},
},
An instance then exposes the named relation directly:
const post = await Post.find(id)
await post.tags().sync(tagIds)
await post.tags().detach()
The legacy array form remains supported. Prefer the named form when the pivot
has custom keys, columns, defaults, timestamps, or uniqueness. Run
buddy generate:migrations after changing pivot metadata.
Computed properties and scopes
get: {
fullName: (model) => `${model.firstName} ${model.lastName}`,
},
set: {
password: (value) => makeHash(value),
},
scopes: {
published: (query) => query.where('status', 'published'),
},
Workflow
buddy make:model Product # scaffold app/Models/Product.ts
buddy generate:migrations # diff models against the schema, emit SQL
# review the generated file in database/migrations/
buddy migrate # apply it
buddy migrate:fresh --seed # dev only: drop, re-migrate, seed
Models resolve at runtime through createModel() from bun-query-builder -
there is no build step between editing a model and querying it. Only migrations
need generating.
Seeding
Seed data is declared on the model, through the useSeeder trait plus the
per-attribute factory functions:
traits: {
useSeeder: {
count: 20,
// Optional: pin specific rows over the generated ones. Keys use the
// model's camelCase attribute names.
fixtures: [
{ name: 'Flagship Widget', status: 'published' },
],
},
},
buddy seed walks every model carrying the trait and fills its table from the
attribute factories. Model fixture data needs no separate seeder or registration.
Idempotent application bootstrap work can live in database/seeders as a
default-exported class extending Seeder from @stacksjs/database. Buddy runs
those application seeders after the model factories.
buddy seed # every model with a useSeeder trait
buddy seed --fresh # truncate each table first
buddy seed --only Product,Review # just these models
buddy seed --except User # everything but these
buddy seed --include-defaults # framework built-ins too
A model with no useSeeder trait is never seeded. Auth and OAuth models are
skipped on a non-fresh database so re-seeding cannot invalidate live sessions -
pass --allow-protected to override.
Built-in models by category
The ones below are worth knowing by name. They are a selection, not the set:
storage/framework/defaults/app/Models/ holds 103, and that directory is the
authority. This section said "All 62 built-in models by category" while
listing fewer than that against 102 on disk, so an agent reading to the end
had no way to tell it was short.
No count of what this section itself lists, deliberately - that number is
maintained by hand, drifts the moment anyone adds a bullet, and is the same
habit that produced the "All 62". The total above is pinned by
buddy docs:agent-counts.
Run find storage/framework/defaults/app/Models -name '*.ts' for the full
list, or buddy list for what a given project resolves.
Users & Auth
- User — name, email, password | traits: useAuth(passkey), useUuid, useTimestamps, useSocials(github) | hasOne: Subscriber, Driver, Author | hasMany: PersonalAccessToken, Customer
- Author — name, email | belongsTo: User | hasMany: Post
- Customer — name, email, phone, totalSpent, lastOrder, status, avatar | belongsTo: User | hasMany: Order, GiftCard, Review, Payment
- Driver — name, phone, vehicleNumber, license, status | belongsTo: User | hasMany: DeliveryRoute
- Subscriber — email, status, source | belongsTo: User | hasMany: SubscriberEmail
Content
- Post — title, content, poster, excerpt, views, publishedAt, status, isFeatured | belongsTo: Author | traits: categorizable, taggable, commentable | seeder: 20
- Page — similar to Post with taggable, categorizable
- Comment — author info, approval, content fields
- Tag — name(unique), slug(unique), description, postCount, color | seeder: 15
- Category — name, description, slug, imageUrl, isActive, parentCategoryId, displayOrder | hasMany: Product | seeder: 10
Commerce (20+ models)
- Product — name(max100), description, price(min1), imageUrl, isAvailable, inventoryCount, preparationTime, allergens(JSON), nutritionalInfo(JSON) | belongsTo: Category, Manufacturer | hasMany: Review, ProductUnit, ProductVariant, LicenseKey, WaitlistProduct, Coupon | seeder: 10, dashboard: highlighted
- ProductVariant — SKU, options, pricing
- ProductUnit — unit-specific pricing
- Cart — status(active|abandoned|converted|expired), totalItems, subtotal, taxAmount, discountAmount, total, expiresAt, currency(USD), notes | hasMany: CartItem | belongsTo: Customer, Coupon
- CartItem — quantity(min1), unitPrice, totalPrice, taxRate, taxAmount, discountPercentage, productName, productSku | belongsTo: Cart
- Order — status, totalAmount, taxAmount, discountAmount, deliveryFee, tipAmount, orderType(DINE_IN|TAKEOUT|DELIVERY), deliveryAddress, specialInstructions | hasMany: OrderItem, Payment | belongsTo: Customer, Coupon | observe: true | seeder: 20
- OrderItem — quantity(min1), price(min0), specialInstructions | belongsTo: Order, Product
- Coupon — code(unique), discountType(fixed_amount|percentage), discountValue, minOrderAmount, usageLimit, usageCount, startDate, endDate | seeder: 15
- GiftCard — code(unique), initialBalance, currentBalance, currency, status, recipientEmail, isDigital, isReloadable, expiryDate | seeder: 20
- Manufacturer — manufacturer info
- Review — rating(1-5), title, content(max2000), isVerifiedPurchase, isApproved, isFeatured, helpfulVotes, unhelpfulVotes | belongsTo: Product, Customer | seeder: 50
Shipping & Delivery
- ShippingMethod, ShippingRate (weightFrom, weightTo, rate), ShippingZone
- DeliveryRoute — driver, vehicle, stops, totalDistance | belongsTo: Driver
- DigitalDelivery — name, downloadLimit, expiryDays, automaticDelivery
- LicenseKey — key(XXXX-XXXX-XXXX-XXXX-XXXX), template, expiryDate, status
Payments & Financial
- Payment — amount, method(creditCard|debitCard|paypal|...), status(pending|completed|failed|refunded), currency, transactionId(unique) | belongsTo: Order, Customer | seeder: 50
- PaymentMethod, PaymentProduct, PaymentTransaction
- Subscription — type, providerId, providerStatus, unitPrice
- Transaction — standard transaction tracking
- TaxRate — name, rate(0-100), type(VAT|GST|Sales Tax|Customs Duty), country, region, isDefault
Engagement & Marketing
- Notification — type, channel, recipient, subject, body, status(pending|sent|delivered|failed|read) | belongsTo: User | seeder: 30
- Campaign — name, type(email|sms|push|social|multi-channel), status, audienceSize, openRate, clickRate, budget | seeder: 10
- Activity — type, description, subjectType, subjectId, causer, properties(JSON), ipAddress | belongsTo: User | seeder: 50
- EmailList, SocialPost, LoyaltyPoint (walletId, points, source, expiryDate), LoyaltyReward
System
- Job — queue, payload, attempts, available_at, reserved_at | seeder: 15
- FailedJob — failed background jobs
- Error — type, message, stack, status, additionalInfo | seeder: 10
- Log — application logs
- Request — method, path, statusCode, durationMs, ipAddress, memoryUsage, userAgent, errorMessage | seeder: 50
- Websocket — connection tracking
- PrintDevice — name, location, terminal, lastPing, printCount, isActive
- WaitlistProduct, WaitlistRestaurant — waitlist tracking
- Receipt — receipt records
CLI Commands
buddy make:model [name] — scaffold a model in app/Models/
buddy publish:model [name] — copy a built-in model into app/Models/ to override it
buddy generate:migrations — diff models against the schema and emit SQL
buddy migrate / buddy migrate:fresh --seed — apply migrations
buddy make:migration [name] — hand-write a migration instead
buddy make:factory [name] — standalone factory
buddy seed — seed every model carrying a useSeeder trait
Gotchas
- No code generation step for models.
defineModel() calls createModel()
from bun-query-builder at runtime, so a model is queryable the moment you save
it. Only migrations are generated.
- Migrations come from models. Change the model, run
buddy generate:migrations,
review the SQL, then buddy migrate. Editing a generated migration by hand
will be overwritten by the next diff.
commentable, not commentables. define-model only checks the singular
key. The plural spelling used to type check while leaving the trait inert.
- Seeding is model-declared.
useSeeder sets the count and fixtures; the
per-attribute factory functions produce the values. There are no seeder
files to write or register.
hidden is serialization, guarded is mass assignment. They are different
protections; a password wants both hidden and no fillable.
validation.rule is mandatory on every attribute - it drives both request
validation and the inferred column type.
- Dashboard-highlighted models (
dashboard: { highlight: true }) appear
prominently in the admin UI.
1---2name: stacks-models-43description: Use when working with data models in Stacks - the defineModel() API, model attributes with validation and factories, relationships (hasOne/hasMany/belongsTo/belongsToMany), traits (useAuth, useUuid, useTimestamps, useSearch, useApi, billable, taggable, categorizable, commentable, likeable, observe), computed properties (get/set), model generation, and the 103 built-in framework models. Covers model definitions 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-models-49---1011# Stacks Models1213## Key Paths14- Your models: `app/Models/` (create it; it does not exist in a fresh project)15- Built-in models: `storage/framework/defaults/app/Models/` (62 files, grouped16 into `commerce/`, `Content/`, `realtime/` and a flat top level)17- `ModelOptions` / `Attribute` types: `storage/framework/core/types/src/model.ts`18- Attribute presets: `storage/framework/types/attributes.ts`1920To customize a built-in model, create the same filename under `app/Models/` -21`app/Models/User.ts` wins over the default. `buddy publish:model User` copies the22default across as a starting point.2324## Writing a model2526Everything - schema, validation, factory, relationships, behavior - is declared27in one `defineModel()` call. Migrations are derived from this; you do not write28the SQL.2930```ts31// app/Models/Product.ts32import { defineModel } from '@stacksjs/orm'33import { schema } from '@stacksjs/validation'3435export default defineModel({36 name: 'Product', // defaults to the file name37 table: 'products', // defaults to lowercase plural of `name`38 primaryKey: 'id', // default39 autoIncrement: true, // default4041 traits: {42 useUuid: true,43 useTimestamps: true,44 useApi: { uri: 'products', routes: ['index', 'store', 'show', 'update', 'destroy'] },45 useSearch: { searchable: ['name'], filterable: ['status'] },46 observe: true,47 },4849 belongsTo: ['Category'],50 hasMany: ['Review'],5152 attributes: {53 name: {54 required: true,55 fillable: true,56 order: 1,57 validation: {58 rule: schema.string().min(3).max(100),59 message: { max: 'Name must have a maximum of 100 characters' },60 },61 factory: faker => faker.commerce.productName(),62 },63 status: {64 required: true,65 fillable: true,66 default: 'draft',67 validation: { rule: schema.enum(['draft', 'published', 'archived']) },68 factory: faker => faker.helpers.arrayElement(['draft', 'published', 'archived']),69 },70 },71} as const)72```7374`as const` is what the built-in models use - it narrows literal types so the75generated model types stay precise.7677### Attribute fields7879`validation.rule` is the only required key on an attribute.8081| Field | Effect |82|---|---|83| `required` | Value required; emits a `NOT NULL` column |84| `nullable` | Explicit nullability override |85| `default` | Column default (`string \| number \| boolean \| Date`) |86| `unique` | Unique constraint |87| `type` | Force the column type instead of inferring from the rule |88| `order` | Column order in the table and in dashboard forms |89| `fillable` | Allow mass assignment |90| `guarded` | Block mass assignment |91| `hidden` | Exclude from JSON serialization (passwords, tokens) |92| `foreignKey` | Disable, infer, or configure the FK constraint |93| `factory` | `(faker) => value`, used by seeders and tests |94| `validation` | `{ rule, message? }` - `rule` from `schema`, `message` keyed by rule name |9596### Traits9798| Trait | What it adds |99|---|---|100| `useUuid` | UUID column alongside the primary key |101| `useTimestamps` (alias `timestampable`) | `created_at` / `updated_at`. On by default |102| `useSoftDeletes` (alias `softDeletable`) | `deleted_at` plus soft-delete query scopes |103| `useAuth` (alias `authenticatable`) | Auth columns; `{ usePasskey: true }` adds passkeys. Also confers `morphMany: { tokenable: 'PersonalAccessToken' }`, so any authenticatable model can hold API tokens |104| `useApi` | Generates REST actions and routes: `{ uri, routes, middleware? }` |105| `useSearch` (alias `searchable`) | Search-engine indexing: `{ displayable, searchable, sortable, filterable }` |106| `useSocials` | OAuth identities, e.g. `['github']` |107| `useActivityLog` | Writes an `activities` feed row per change: `{ logOnly }` / `{ include }` / `{ exclude }` pick the attributes |108| `useAudit` | Writes a `model_audits` row per change with an old/new diff |109| `observe` | Emits `{model}:created` / `:updated` / `:deleted` events |110| `billable` | Stripe methods (`checkout()`, `activeSubscription()`, ...) |111| `taggable` / `categorizable` / `commentable` / `likeable` | Pivot tables and their relation methods |112113Also at the top level: `indexes: [{ name, columns, unique?, where? }]` for114composite and partial-unique indexes, and `dashboard: { highlight: true }` to115feature the model in the admin UI.116117`useApi` is an API capability, not a dashboard-view generator. Its generated118routes are registered from the merged model registry. Framework defaults are119loaded first, then recursive `app/Models/` definitions override matching model120names. Protect non-public resources at the model:121122```ts123useApi: {124 uri: 'mail-preferences',125 routes: ['index', 'store', 'show', 'update', 'destroy'],126 middleware: ['auth'],127}128```129130Dashboard-specific endpoints may still use scoped Actions when their transport131shape, authorization boundary, or aggregation differs from generic CRUD. Do132not expose a sensitive model through unguarded generated routes just because a133separate dashboard endpoint is protected.134135Generated store and update routes accept both spellings of every fillable136attribute and each foreign key implied by `belongsTo`. Declaring Product as a137belongs-to relation therefore accepts `productId` or `product_id` without138duplicating that relationship column as an attribute.139140### Relationships141142`hasOne`, `hasMany`, `belongsTo`, `belongsToMany`, `hasOneThrough`,143`hasManyThrough`, `morphOne`, `morphMany`, `morphTo`, `morphToMany`,144`morphedByMany`. Each takes an array of model names, or an object form when you145need to name the foreign key.146147The object form is also where a `belongsTo` says what happens to its row when148the row it points at is deleted:149150```ts151belongsTo: [152 { model: 'Repository', onDelete: 'cascade' },153 { model: 'User', foreignKey: 'author_id', onDelete: 'set null' },154],155```156157`'cascade' | 'set null' | 'restrict' | 'no action'`, enforced by the database158on the foreign key. Left off, the default applies: the delete is refused while159a child still points at the row.160161Worth declaring rather than deleting children in application code. The order162has to be right in every place that deletes, forever, and the place that misses163one leaves rows nothing can reach - while the database applies the rule to164deletes the application never made: a manual `DELETE`, a restore, another165service sharing the schema. Not for a polymorphic pair (`commentable_id`166beside `commentable_type`): those carry no foreign key at all, because a167constraint would name one table and reject every row pointing at another.168169Use the named object form for a many-to-many relation that owns its pivot170schema. It keeps the relation accessor, migration, pivot defaults, timestamps,171and uniqueness in the model definition:172173```ts174belongsToMany: {175 tags: {176 model: 'Tag',177 table: 'taggable_models',178 foreignKey: 'taggable_id',179 relatedKey: 'tag_id',180 pivot: {181 columns: {182 taggable_type: { default: 'posts' },183 },184 timestamps: true,185 uniques: [['tag_id', 'taggable_id', 'taggable_type']],186 },187 },188},189```190191An instance then exposes the named relation directly:192193```ts194const post = await Post.find(id)195await post.tags().sync(tagIds)196await post.tags().detach()197```198199The legacy array form remains supported. Prefer the named form when the pivot200has custom keys, columns, defaults, timestamps, or uniqueness. Run201`buddy generate:migrations` after changing pivot metadata.202203### Computed properties and scopes204205```ts206get: {207 fullName: (model) => `${model.firstName} ${model.lastName}`,208},209set: {210 password: (value) => makeHash(value),211},212scopes: {213 published: (query) => query.where('status', 'published'),214},215```216217## Workflow218219```sh220buddy make:model Product # scaffold app/Models/Product.ts221buddy generate:migrations # diff models against the schema, emit SQL222# review the generated file in database/migrations/223buddy migrate # apply it224buddy migrate:fresh --seed # dev only: drop, re-migrate, seed225```226227Models resolve at runtime through `createModel()` from `bun-query-builder` -228there is no build step between editing a model and querying it. Only migrations229need generating.230231## Seeding232233Seed data is declared on the model, through the `useSeeder` trait plus the234per-attribute `factory` functions:235236```ts237traits: {238 useSeeder: {239 count: 20,240 // Optional: pin specific rows over the generated ones. Keys use the241 // model's camelCase attribute names.242 fixtures: [243 { name: 'Flagship Widget', status: 'published' },244 ],245 },246},247```248249`buddy seed` walks every model carrying the trait and fills its table from the250attribute factories. Model fixture data needs no separate seeder or registration.251Idempotent application bootstrap work can live in `database/seeders` as a252default-exported class extending `Seeder` from `@stacksjs/database`. Buddy runs253those application seeders after the model factories.254255```bash256buddy seed # every model with a useSeeder trait257buddy seed --fresh # truncate each table first258buddy seed --only Product,Review # just these models259buddy seed --except User # everything but these260buddy seed --include-defaults # framework built-ins too261```262263A model with no `useSeeder` trait is never seeded. Auth and OAuth models are264skipped on a non-fresh database so re-seeding cannot invalidate live sessions -265pass `--allow-protected` to override.266267## Built-in models by category268269The ones below are worth knowing by name. They are a selection, not the set:270`storage/framework/defaults/app/Models/` holds 103, and that directory is the271authority. This section said "All 62 built-in models by category" while272listing fewer than that against 102 on disk, so an agent reading to the end273had no way to tell it was short.274275No count of what this section itself lists, deliberately - that number is276maintained by hand, drifts the moment anyone adds a bullet, and is the same277habit that produced the "All 62". The total above is pinned by278`buddy docs:agent-counts`.279280Run `find storage/framework/defaults/app/Models -name '*.ts'` for the full281list, or `buddy list` for what a given project resolves.282283### Users & Auth284- **User** — name, email, password | traits: useAuth(passkey), useUuid, useTimestamps, useSocials(github) | hasOne: Subscriber, Driver, Author | hasMany: PersonalAccessToken, Customer285- **Author** — name, email | belongsTo: User | hasMany: Post286- **Customer** — name, email, phone, totalSpent, lastOrder, status, avatar | belongsTo: User | hasMany: Order, GiftCard, Review, Payment287- **Driver** — name, phone, vehicleNumber, license, status | belongsTo: User | hasMany: DeliveryRoute288- **Subscriber** — email, status, source | belongsTo: User | hasMany: SubscriberEmail289290### Content291- **Post** — title, content, poster, excerpt, views, publishedAt, status, isFeatured | belongsTo: Author | traits: categorizable, taggable, commentable | seeder: 20292- **Page** — similar to Post with taggable, categorizable293- **Comment** — author info, approval, content fields294- **Tag** — name(unique), slug(unique), description, postCount, color | seeder: 15295- **Category** — name, description, slug, imageUrl, isActive, parentCategoryId, displayOrder | hasMany: Product | seeder: 10296297### Commerce (20+ models)298- **Product** — name(max100), description, price(min1), imageUrl, isAvailable, inventoryCount, preparationTime, allergens(JSON), nutritionalInfo(JSON) | belongsTo: Category, Manufacturer | hasMany: Review, ProductUnit, ProductVariant, LicenseKey, WaitlistProduct, Coupon | seeder: 10, dashboard: highlighted299- **ProductVariant** — SKU, options, pricing300- **ProductUnit** — unit-specific pricing301- **Cart** — status(active|abandoned|converted|expired), totalItems, subtotal, taxAmount, discountAmount, total, expiresAt, currency(USD), notes | hasMany: CartItem | belongsTo: Customer, Coupon302- **CartItem** — quantity(min1), unitPrice, totalPrice, taxRate, taxAmount, discountPercentage, productName, productSku | belongsTo: Cart303- **Order** — status, totalAmount, taxAmount, discountAmount, deliveryFee, tipAmount, orderType(DINE_IN|TAKEOUT|DELIVERY), deliveryAddress, specialInstructions | hasMany: OrderItem, Payment | belongsTo: Customer, Coupon | observe: true | seeder: 20304- **OrderItem** — quantity(min1), price(min0), specialInstructions | belongsTo: Order, Product305- **Coupon** — code(unique), discountType(fixed_amount|percentage), discountValue, minOrderAmount, usageLimit, usageCount, startDate, endDate | seeder: 15306- **GiftCard** — code(unique), initialBalance, currentBalance, currency, status, recipientEmail, isDigital, isReloadable, expiryDate | seeder: 20307- **Manufacturer** — manufacturer info308- **Review** — rating(1-5), title, content(max2000), isVerifiedPurchase, isApproved, isFeatured, helpfulVotes, unhelpfulVotes | belongsTo: Product, Customer | seeder: 50309310### Shipping & Delivery311- **ShippingMethod**, **ShippingRate** (weightFrom, weightTo, rate), **ShippingZone**312- **DeliveryRoute** — driver, vehicle, stops, totalDistance | belongsTo: Driver313- **DigitalDelivery** — name, downloadLimit, expiryDays, automaticDelivery314- **LicenseKey** — key(XXXX-XXXX-XXXX-XXXX-XXXX), template, expiryDate, status315316### Payments & Financial317- **Payment** — amount, method(creditCard|debitCard|paypal|...), status(pending|completed|failed|refunded), currency, transactionId(unique) | belongsTo: Order, Customer | seeder: 50318- **PaymentMethod**, **PaymentProduct**, **PaymentTransaction**319- **Subscription** — type, providerId, providerStatus, unitPrice320- **Transaction** — standard transaction tracking321- **TaxRate** — name, rate(0-100), type(VAT|GST|Sales Tax|Customs Duty), country, region, isDefault322323### Engagement & Marketing324- **Notification** — type, channel, recipient, subject, body, status(pending|sent|delivered|failed|read) | belongsTo: User | seeder: 30325- **Campaign** — name, type(email|sms|push|social|multi-channel), status, audienceSize, openRate, clickRate, budget | seeder: 10326- **Activity** — type, description, subjectType, subjectId, causer, properties(JSON), ipAddress | belongsTo: User | seeder: 50327- **EmailList**, **SocialPost**, **LoyaltyPoint** (walletId, points, source, expiryDate), **LoyaltyReward**328329### System330- **Job** — queue, payload, attempts, available_at, reserved_at | seeder: 15331- **FailedJob** — failed background jobs332- **Error** — type, message, stack, status, additionalInfo | seeder: 10333- **Log** — application logs334- **Request** — method, path, statusCode, durationMs, ipAddress, memoryUsage, userAgent, errorMessage | seeder: 50335- **Websocket** — connection tracking336- **PrintDevice** — name, location, terminal, lastPing, printCount, isActive337- **WaitlistProduct**, **WaitlistRestaurant** — waitlist tracking338- **Receipt** — receipt records339340## CLI Commands341- `buddy make:model [name]` — scaffold a model in `app/Models/`342- `buddy publish:model [name]` — copy a built-in model into `app/Models/` to override it343- `buddy generate:migrations` — diff models against the schema and emit SQL344- `buddy migrate` / `buddy migrate:fresh --seed` — apply migrations345- `buddy make:migration [name]` — hand-write a migration instead346- `buddy make:factory [name]` — standalone factory347- `buddy seed` — seed every model carrying a `useSeeder` trait348349## Gotchas350- **No code generation step for models.** `defineModel()` calls `createModel()`351 from bun-query-builder at runtime, so a model is queryable the moment you save352 it. Only migrations are generated.353- **Migrations come from models.** Change the model, run `buddy generate:migrations`,354 review the SQL, then `buddy migrate`. Editing a generated migration by hand355 will be overwritten by the next diff.356- **`commentable`, not `commentables`.** `define-model` only checks the singular357 key. The plural spelling used to type check while leaving the trait inert.358- **Seeding is model-declared.** `useSeeder` sets the count and fixtures; the359 per-attribute `factory` functions produce the values. There are no seeder360 files to write or register.361- **`hidden` is serialization, `guarded` is mass assignment.** They are different362 protections; a password wants both `hidden` and no `fillable`.363- **`validation.rule` is mandatory** on every attribute - it drives both request364 validation and the inferred column type.365- Dashboard-highlighted models (`dashboard: { highlight: true }`) appear366 prominently in the admin UI.