Skip to main content

Standard Model Methods

Hysteria ORM models provide a rich set of static methods for interacting with your database. These methods are fully type-safe and support advanced options. Standard methods are type safe since only model columns are allowed to be selected.

CRUD Methods

find

Fetch multiple records matching criteria.

const users = await User.find({ where: { status: 'active' } });

const usersWithNameAndEmail = await User.find({
select: ["name", "email"],
}); // { name: string, email: string }[]

findOne

Fetch a single record matching criteria.

const user = await User.findOne({ where: { email: 'john@example.com' } });

const userWithNameAndEmail = await User.findOne({
select: ["name", "email"],
}); // { name: string, email: string } | null

findOneOrFail

Fetch a single record or throw if not found.

const user = await User.findOneOrFail({ where: { email: 'john@example.com' } });

insert

Insert a new record.

const user = await User.insert({ name: 'John', email: 'john@example.com' });

insertMany

Insert multiple records.

const users = await User.insertMany([
{ name: 'John', email: 'john@example.com' },
{ name: 'Jane', email: 'jane@example.com' },
]);

updateRecord

Update a record by primary key.

user.name = 'Johnny';
const updated = await User.updateRecord(user);

deleteRecord

Delete a record by primary key.

await User.deleteRecord(user);

firstOrInsert

Find a record or create it if it doesn't exist.

// First argument: search criteria
// Second argument: data to insert if not found
const user = await User.firstOrInsert(
{ email: 'john@example.com' },
{ name: 'John', email: 'john@example.com', status: 'active' }
);

upsert

Insert or update a record based on conflict keys (QueryBuilder only).

const [post] = await sql.query('posts').upsert(
{ id: uuid, title: 'Title', content: 'Content' }, // data
{ id: uuid }, // conflict keys
{ returning: ['id', 'title'] } // options
);

upsertMany

Insert or update multiple records (QueryBuilder only).

await sql.query('posts').upsertMany(
['id'], // conflict columns
['title', 'content'], // columns to update on conflict
[
{ id: uuid1, title: 'First', content: 'Content 1' },
{ id: uuid2, title: 'Second', content: 'Content 2' },
]
);

Best Practices

  • Always use the static methods for database operations.
  • Use findOneOrFail for required lookups.
  • Use firstOrInsert and upsert for idempotent operations.

Next: Query Builder