Fetching Data

You must have seen how to build a query chain in tabel ORM in the query-building-section, and the use of methods .all(), and .first() at the end of the query chain. These 2 methods are the ones that actually trigger the an sql query composed from the query chain that preceed these methods, on the database. There are 3 different methods which are provided by tabel ORM to retrieve data of some type from the database. They are:

  1. .all(...args)
  2. .first(...args)
  3. .count(...args)

Each method is covered in detail in this section. But before getting to methods which actually interact with the database, we’d cover a query-chain building method .map first.


.map

.map((row) => ...)

Pretty much similar to javascript’s Array.map. Applies a map on the set of rows scoped by the query chain. Example below:

1
2
3
4
5
const posts = await table('posts')
.where('is_published', true)
.map((row) => ({id: row.id, title: row.title}))
.all()
;

Multiple map operations can be added to a single query-chain. They are applied to the rows in the result set in the order they are added to the query-chain.


.all

.all(...args)

Fetchs an array of objects from the database, where each object represents a row of the scoped result-set. Returns a Promise. Can take the same arguments that the .where query-building method takes, and append a where clause to the query-chain based on its arguments. Returned Promise resolves to an empty array when no rows are scoped. Example below:

1
2
const postsViaWhereArgs = await table('posts').where('is_published', true).all();
const postsViaAllArgs = await table('posts').all('is_published', true);


.first

.first(...args)

Fetches a single object from the database which represents the first row of the scoped result-set. Returns a Promise. Can take the same arguments that the .wherequery-building method takes, and append a where clause to the query-chain based on its arguments. Adds a .limit(1) clause to the query chain before fetching data. Returned Promise resolves to null when no rows are scoped Example below:

1
2
const postViaWhereArgs = await table('posts').where('created_at', '>', someDate()).first();
const postViaAllArgs = await table('posts').first('created_at', '>', someDate());


.count

.count(...args)

Fetches count of scoped rows from the database. Returns a Promise which resolves to an int. This .count is not your conventional sql-count. It creates a query from the query-chain, and wraps it in a count(*) from (query-from-query-chain) as t1 sql statement. This way, .count returns the count of scoped rows even if your query-chain contains a groupBy clause. Can take the same arguments as the .where, and append a where clause to the query-chain based on its arguments. Example below:

1
2
const countViaWhereArgs = await table('posts').where('is_published', true).count();
const countViaCountArgs = await table('posts').count('is_published', true);


Next > Mutating Data