Model API
The ActiveRecord-style Model class generated by OmniSvelte for every .schema.ts file.
Model API
OmniSvelte generates a Model class for every .schema.ts file. The model wraps Drizzle ORM with an ActiveRecord-style API while still giving you a full escape hatch to raw Drizzle when needed.
Import
ts
import { Posts } from '$models/posts.model'; // single model
import { Posts, Users } from '$models'; // barrel — all modelsStatic methods
find(id)
ts
const post = await Posts.find(1);
// Returns Post | nullfindMany(options?)
ts
const posts = await Posts.findMany({
where: { published: true },
orderBy: { createdAt: 'desc' },
limit: 10,
offset: 0
});create(data)
ts
const post = await Posts.create({
title: 'Hello World',
slug: 'hello-world',
content: 'My first post',
userId: 1
});
// Returns Post (with generated id, createdAt, updatedAt)query() — fluent query builder
ts
const posts = await Posts
.query()
.where('published', true)
.where('userId', userId)
.orderBy('created_at', 'desc')
.limit(10)
.get();drizzle()
Escape hatch to the raw Drizzle instance:
ts
const db = Posts.drizzle();
const result = await db
.select({ id: posts.id, title: posts.title })
.from(posts)
.innerJoin(users, eq(posts.userId, users.id))
.where(and(eq(posts.published, true), gt(posts.createdAt, cutoff)));Instance methods
ts
const post = await Posts.find(1);
// Update
await post.update({ title: 'Updated Title' });
// Delete
await post.delete();
// Serialize (respects `hidden` config)
const json = post.toJSON();Relationships
Defined in your schema or model file:
ts
// src/lib/posts.schema.ts
defineSchema('posts', fields, {
relationships: {
author: { type: 'belongsTo', model: 'users', foreignKey: 'userId' },
comments: { type: 'hasMany', model: 'comments', foreignKey: 'postId' },
tags: { type: 'belongsToMany', through: 'postTags', model: 'tags' }
}
});Use with:
ts
const post = await Posts.with(['author', 'comments']).find(1);
console.log(post.author.name);
console.log(post.comments.length);Factories (testing)
ts
import { PostFactory } from '$lib/db/models/posts.factory';
// Generate unsaved plain object
const data = PostFactory.make({ published: true });
// Create and persist to DB
const post = await PostFactory.create({ userId: testUser.id });
// Create many
const posts = await PostFactory.createMany(5);createModel (manual)
If you need a model without code generation:
ts
import { createModel } from 'omni-svelte/database';
import { db } from '$db';
import { posts } from '$schema';
export const PostModel = createModel(db, posts, {
primaryKey: 'id',
timestamps: true
});