Skip to content

examples_orm

Rafael Corrêa Chaves edited this page Jul 26, 2021 · 1 revision

Here you can check all (or most) of the examples on how to use our query builder/ORM.

Insert

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

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();

Delete

You can easily delete your model using delete method, erasing it from the database

const user = await User.find("your-id");
await user.delete();

Querying

Get

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 */);

First

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];

Last

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();

Special methods

avg

const avg: number = await User.query().avg("count");

count

const count: number = await User.query().count();

Clone this wiki locally