Docs/Guides/Database

Advanced query patterns

The model query builder wraps Knex and exposes the underlying builder through toKnex(). Use the higher-level model API for ordinary queries and drop to Knex only when the query…

1 min read

The model query builder wraps Knex and exposes the underlying builder through toKnex(). Use the higher-level model API for ordinary queries and drop to Knex only when the query genuinely needs lower-level features.

Grouped conditions#

ts
const articles = await Article.query()
  .where((query) => {
    query.where("status", "published").orWhere("status", "scheduled");
  })
  .orderBy("createdAt", "desc")
  .get();

Access the Knex builder#

ts
const query = Article.query().where("status", "published").toKnex();
const rows = await query.select("id", "title");

When using raw SQL, bind values as parameters. Never concatenate user-controlled values into SQL identifiers or raw fragments. Parameter binding protects values, but identifiers often need explicit allow-lists.

Local scopes#

The query builder can dispatch model methods named scope<Name> when a matching method is called on the query proxy. Keep scope methods composable and test them with realistic data. For security-sensitive global scopes, ensure callers cannot accidentally bypass tenant or authorization boundaries.

Pagination and performance#

The package exports PaginationResult<T> with data, total, perPage, currentPage, and lastPage. Confirm the installed builder's pagination signature. Index columns used in filters and sorting, inspect query plans for large tables, and avoid unbounded all() calls on user-facing endpoints.

veap
Preparing0%