Flexible Search
Using the Model.search()
method, you can perform object-based flexible searches.
(The interface is inspired by the Ransack gem.)
Search parameters are specified as an object with keys representing the field name and search condition combination strings, and values representing the search values.
You can include associations in the keys.
The search conditions include eq
, cont
, matches
, lt
, gte
, in
, null
, and more.
In addition, modifiers such as not
, or
, and
, any
, all
are also available.
Please refer to the documentation of the search()
method for more details.
import { User } from "./models/index.js";
const search = User.search({ name_eq: "John", // name equals "John" age_not_null: 1, // age is not null profile_bio_cont: "foo", // related profile's bio contains "foo" email_or_name_cont_any: ["bar", "baz"], // email or name contains "bar" or "baz"});const users = search.result();
Additionally, you can include the names of searchable scopes defined in the searchableScopes
array as keys in the search parameters.
For example, the bio_cont
scope defined as follows can be used in the search parameters:
import { scope } from "accel-record";import { ApplicationRecord } from "./applicationRecord.js";
class UserModel extends ApplicationRecord { @scope static bio_cont(value: string) { return this.joins("profile").where({ profile: { bio: { contains: value } }, }); } static searchableScopes = ["bio_cont"];}
import { User } from "./models/index.js";
const search = User.search({ bio_cont: "foo" }); // profile's bio contains "foo"const users = search.result();