TinyBase logoTinyBase β

JoinedAs

The JoinedAs type describes an object returned from calling a Join function so that the joined Table Id can be optionally aliased.

{as: (joinedTableId: Id) => void}
TypeDescription
as(joinedTableId: Id) => void

A function that lets you specify an alias for the joined Table Id.

Note that if two Join clauses are both aliased to the same name (or if you create two joins to the same underlying Table, both without aliases), only the latter of two will be used in the query.

For the purposes of clarity, it's recommended to use an alias that does not collide with a real underlying Table (whether included in the query or not).

Example

This example shows a query that joins the same underlying Table twice, for different purposes. Both joins are aliased with the 'as' function to disambiguate them. Note that the selected Cells are also aliased.

import {createQueries, createStore} from 'tinybase';

const store = createStore()
  .setTable('pets', {
    fido: {species: 'dog', buyerId: '1', sellerId: '2'},
    felix: {species: 'cat', buyerId: '2'},
    cujo: {species: 'dog', buyerId: '3', sellerId: '1'},
  })
  .setTable('humans', {
    '1': {name: 'Alice'},
    '2': {name: 'Bob'},
    '3': {name: 'Carol'},
  });

const queries = createQueries(store);
queries.setQueryDefinition('query', 'pets', ({select, join}) => {
  select('buyers', 'name').as('buyer');
  select('sellers', 'name').as('seller');
  // from pets
  join('humans', 'buyerId').as('buyers');
  join('humans', 'sellerId').as('sellers');
});

queries.forEachResultRow('query', (rowId) => {
  console.log({[rowId]: queries.getResultRow('query', rowId)});
});
// -> {fido: {buyer: 'Alice', seller: 'Bob'}}
// -> {felix: {buyer: 'Bob'}}
// -> {cujo: {buyer: 'Carol', seller: 'Alice'}}

Since

v2.0.0