Repository navigation
examples_orm
Here you can check all (or most) of the examples on how to use our query builder/ORM.
You can simply create an instance, açaí will check if it's already database initialized and insert/update accordingly. In the case below, since you started a new instance, it will insert and retrieve the ID of this model.
const user = new User();
user.name = "John Doe";
await user.save();Or you can directly create from the class method and get back the user instance.
const user = await User.insert({ /* fields * });Insert many rows is also an option, it will return all models created
const users: User[] = await User.insertMany([
{ /* fields */ },
{ /* fields */ },
]);Update happens automatically when the model is already saved from the database (or through retrieval, or having save being called before)
const user = await User.find("your-id");
user.name = "Brand new name";
// this time it will update instead of insert
await user.save();const user = new User();
user.name = "Initial name";
// this will insert
await user.save();
user.name = "Brand new name";
// this time it will update
await user.save();You can easily delete your model using delete method, erasing it from the database
const user = await User.find("your-id");
await user.delete();Get will allow you to get many instances of the model, it has access to where clauses, limit, offset, etc.
const users: User[] = await User.query().where("field1", "value").get();Doing a and where clause
const users: User[] = await User.query().where("field1", "value").where("field2", "value").get();Doing a or where clause
const users: User[] = await User.query().where("field1", "value").orWhere("field2", "value").get();There are other tons of where like methods, such as:
whereIn,whereNotIn,whereNull,whereNotNull, and it's or variants.
Limit query rows
const users: User[] = await User.query().limit(5, /* Optional arguments to offset by ITEM quantity */).get();
// this is the same as doing
await User.query().paginate(5, /* Optional arguments to offset by PAGE */);
// or
await User.paginate(5, /* Optional arguments to offset by PAGE */);Will only get first row
const user: User = await User.query().where("field1", "value").first();
// same as
(await User.query().where("field1", "value").limit(1).get())[0];You can also get the last row with last
const user: User = await User.query().last();
// same as
(await User.query().limit(1).orderBy("id", "DESC").get())[0];
// or as
await User.query().orderBy("id", "DESC").first();const avg: number = await User.query().avg("count");const count: number = await User.query().count();Copyright (c) 2021 APO Softworks. All rights reserved. Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.