Pular para o conteúdo

Filtros e Operadores

O where do Mirror aceita tanto igualdade simples quanto operadores para comparações complexas. Todos os operadores são funções importadas de mirror-orm e são totalmente tipados.


Valores passados diretamente geram uma comparação por igualdade (=):

await repo.find({
where: {
status: 'active',
role: 'admin',
}
// WHERE status = $1 AND role = $2
});

Condições dentro do mesmo objeto são unidas com AND:

where: { role: 'admin', active: true }
// WHERE role = $1 AND active = $2

Passar um array une cada objeto com OR. Dentro de cada objeto, as condições continuam sendo AND:

where: [
{ role: 'admin' },
{ role: 'moderator', active: true },
]
// WHERE (role = $1) OR (role = $2 AND active = $3)

import { MoreThan, MoreThanOrEqual, LessThan, LessThanOrEqual, Not, Between } from 'mirror-orm';
OperadorSQL geradoExemplo
MoreThan(v)col > $NMoreThan(18)
MoreThanOrEqual(v)col >= $NMoreThanOrEqual(18)
LessThan(v)col < $NLessThan(65)
LessThanOrEqual(v)col <= $NLessThanOrEqual(65)
Not(v)col != $NNot('banned')
Between(a, b)col BETWEEN $N AND $MBetween(18, 30)
await repo.find({
where: {
age: Between(18, 60),
score: MoreThanOrEqual(70),
role: Not('banned'),
}
});

import { Like, ILike } from 'mirror-orm';
OperadorSQL geradoComportamento
Like(v)col LIKE $NCase-sensitive, suporta % e _
ILike(v)col ILIKE $NCase-insensitive — PostgreSQL only
await repo.find({ where: { name: Like('%silva%') } });
// WHERE name LIKE $1 → $1 = '%silva%'
await repo.find({ where: { email: ILike('%@GMAIL.COM') } });
// WHERE email ILIKE $1

import { In } from 'mirror-orm';
OperadorSQL gerado
In([...])col IN ($1, $2, ...)
await repo.find({
where: { status: In(['active', 'pending', 'review']) }
});
// WHERE status IN ($1, $2, $3)

Não existe NotIn. Para o efeito contrário, use Raw: Raw(col => \${col} NOT IN (‘a’, ‘b’)`)`


import { IsNull, IsNotNull } from 'mirror-orm';
OperadorSQL gerado
IsNull()col IS NULL
IsNotNull()col IS NOT NULL
await repo.find({ where: { deletedAt: IsNull() } });
// WHERE deleted_at IS NULL
await repo.find({ where: { verifiedAt: IsNotNull() } });
// WHERE verified_at IS NOT NULL

Disponíveis apenas para colunas JSONB no PostgreSQL.

import { JsonContains, JsonHasKey, JsonHasAllKeys, JsonHasAnyKey } from 'mirror-orm';
OperadorSQL geradoDescrição
JsonContains(obj)col @> $N::jsonbDocumento contém o objeto parcial
JsonHasKey(key)col ? $NDocumento tem a chave
JsonHasAllKeys([...])col ?& $NDocumento tem todas as chaves
JsonHasAnyKey([...])`col ?$N`
// Busca usuários com role 'admin' dentro do JSON
await repo.find({ where: { meta: JsonContains({ role: 'admin' }) } });
// WHERE meta @> $1::jsonb → $1 = '{"role":"admin"}'
// Busca usuários cujo JSON tem a chave 'preferences'
await repo.find({ where: { meta: JsonHasKey('preferences') } });
// Busca usuários cujo JSON tem ambas as chaves 'theme' e 'lang'
await repo.find({ where: { meta: JsonHasAllKeys(['theme', 'lang']) } });

Usar operadores JSON com MySQL, SQLite ou SQL Server lança um erro em runtime.


Para qualquer condição que os operadores não cobrem. Recebe uma função que aceita o nome qualificado da coluna e retorna a expressão SQL completa.

import { Raw } from 'mirror-orm';
// Comparação com subquery
await repo.find({
where: {
score: Raw(col => `${col} > (SELECT AVG(score) FROM results)`),
}
});
// WHERE "results"."score" > (SELECT AVG(score) FROM results)
// Expressão de data nativa do banco
await repo.find({
where: {
createdAt: Raw(col => `${col} > NOW() - INTERVAL '7 days'`),
}
});

Atenção: Raw não aceita parâmetros externos — valores precisam ser interpolados diretamente na string. Se você precisar passar valores dinâmicos com segurança, use o QueryBuilder. Ver Query Builder.


Múltiplos operadores no mesmo objeto são compostos com AND:

await repo.find({
where: {
age: Between(18, 60),
name: ILike('%ana%'),
deletedAt: IsNull(),
status: In(['active', 'verified']),
}
});
// WHERE age BETWEEN $1 AND $2
// AND name ILIKE $3
// AND deleted_at IS NULL
// AND status IN ($4, $5)

Combinando com OR em grupos:

await repo.find({
where: [
{ role: 'admin', deletedAt: IsNull() },
{ role: 'superuser' },
]
});
// WHERE (role = $1 AND deleted_at IS NULL)
// OR (role = $2)

Filtros reutilizáveis definidos diretamente no @Entity. Útil para condições que se repetem em toda a aplicação, como multi-tenancy ou status de publicação.

import { IsNull, MoreThan } from 'mirror-orm';
@Entity('posts', {
filters: {
published: { status: 'published', deletedAt: IsNull() },
recent: { createdAt: MoreThan(new Date(Date.now() - 7 * 86400_000)) },
}
})
class Post {
// ...
}

Ativados pelo nome na query:

// Ativa apenas 'published'
await repo.find({ filters: ['published'] });
// Ativa os dois — combinados com AND
await repo.find({ filters: ['published', 'recent'] });
// Filtros nomeados podem ser combinados com where normal
await repo.find({
filters: ['published'],
where: { authorId: 42 },
});
// WHERE status = 'published' AND deleted_at IS NULL AND author_id = $1

OperadorImportar dePostgreSQLMySQLSQLiteMSSQL
MoreThanmirror-orm
MoreThanOrEqualmirror-orm
LessThanmirror-orm
LessThanOrEqualmirror-orm
Notmirror-orm
Betweenmirror-orm
Likemirror-orm
ILikemirror-orm
Inmirror-orm
IsNullmirror-orm
IsNotNullmirror-orm
JsonContainsmirror-orm
JsonHasKeymirror-orm
JsonHasAllKeysmirror-orm
JsonHasAnyKeymirror-orm
Rawmirror-orm