Relations Overview
Hysteria ORM supports rich relation types between models:
belongsTo
hasOne
hasMany
manyToMany
Relations are retrieved using batch loading, so one query is made for each relation only if withRelation
is called.
Be carefull, too many relation retrieve could slow down you overall query
Example Models
class User extends Model {
@hasMany(() => Post, 'userId')
declare posts: Post[];
@manyToMany(() => Address, () => UserAddress, {
leftForeignKey: 'userId',
rightForeignKey: 'addressId',
})
declare addresses: Address[];
}
class Post extends Model {
@belongsTo(() => User, 'userId')
declare user: User;
}
class Address extends Model {
@manyToMany(() => User, () => UserAddress, {
leftForeignKey: 'addressId',
rightForeignKey: 'userId',
})
declare users: User[];
}
Querying Relations
Eager Loading
const users = await User.query().withRelation('posts').many();
Nested Relations
const users = await User.query().withRelation('posts', Post, (qb) =>
qb.withRelation('user')
).many();
Filtering on Relations
const users = await User.query().withRelation('posts', Post, (qb) =>
qb.where('title', 'Hello World')
).many();
Best Practices
- Use
withRelation
for batch relation loading. - Use callbacks for nested and filtered relations.
- Always define foreign keys explicitly for clarity.
Next: Advanced SQL Features