Relate items
Declare a Relation when two Items have their own lifecycles and one refers to the other. Use this guide instead of the hierarchy when the link is not parent-child, or when an Item links to many others.
Before you start
Section titled “Before you start”- The Templates on both ends, declared as in Define data.
- A Union, declared with
app.addUnion(key, [templates]), when one end accepts several Templates.
-
Declare the Relation. On the from-side Template, call
addRelation(key, cardinality, to, { toKey }). The cardinality is'one-to-one','one-to-many','many-to-one'or'many-to-many', read from the from-side to the to-side.tois a Template or a Union.keynames the Relation on from-side Items andtoKeynames it on to-side Items.toKeydefaults tokey; set it whenever the two directions read differently, as withmanagerandreports.examples/relationships/staffing.ts import type { AppSpec } from '@alpynehq/alpyne-types/builder';import type { ReadAppInstance } from '@alpynehq/alpyne-types/runtime';interface AssignDeskInput {readonly deskId: string;readonly employeeId: string;}interface SetManagerInput {readonly employeeId: string;readonly managerId: string;}interface JoinProjectInput {readonly employeeId: string;readonly projectId: string;}interface IssueAssetInput {readonly assetId: string;readonly employeeId: string;}interface EmployeeInput {readonly employeeId: string;}interface AssetInput {readonly assetId: string;}export const staffApp: AppSpec = (app) => {app.configure('staffing');const employee = app.addTemplate('employee');employee.addProperty('name', 'string');const desk = app.addTemplate('desk');desk.addProperty('label', 'string');const laptop = app.addTemplate('laptop');laptop.addProperty('serial', 'string');const project = app.addTemplate('project');project.addProperty('name', 'string');const asset = app.addUnion('asset', [desk, laptop]);employee.addRelation('desk', 'one-to-one', desk, { toKey: 'occupant' });employee.addRelation('manager', 'many-to-one', employee, { toKey: 'reports' });project.addRelation('members', 'many-to-many', employee, { toKey: 'projects' });employee.addRelation('assets', 'one-to-many', asset, { toKey: 'holder' });const assignDesk = app.addMutation('assignDesk', async (input: AssignDeskInput, current) => {const occupant = await current.templates.employee.getItem(input.employeeId);const target = await current.templates.desk.getItem(input.deskId);if (occupant === undefined || target === undefined) throw new Error('Employee or desk not found');const relation = occupant.relations.desk;if (relation.type !== 'one') throw new Error('Expected a one-side Relation');return await relation.setIfNotExists(target);});assignDesk.input.addProperty('employeeId', 'id').mandatory();assignDesk.input.addProperty('deskId', 'id').mandatory();assignDesk.output.value('boolean').mandatory();const setManager = app.addMutation('setManager', async (input: SetManagerInput, current) => {const report = await current.templates.employee.getItem(input.employeeId);const manager = await current.templates.employee.getItem(input.managerId);if (report === undefined || manager === undefined) throw new Error('Employee not found');const relation = report.relations.manager;if (relation.type !== 'one') throw new Error('Expected a one-side Relation');await relation.set(manager);});setManager.input.addProperty('employeeId', 'id').mandatory();setManager.input.addProperty('managerId', 'id').mandatory();setManager.output.void();const joinProject = app.addMutation('joinProject', async (input: JoinProjectInput, current) => {const team = await current.templates.project.getItem(input.projectId);const member = await current.templates.employee.getItem(input.employeeId);if (team === undefined || member === undefined) throw new Error('Project or employee not found');const relation = team.relations.members;if (relation.type !== 'many') throw new Error('Expected a many-side Relation');return await relation.addIfNotExists(member);});joinProject.input.addProperty('projectId', 'id').mandatory();joinProject.input.addProperty('employeeId', 'id').mandatory();joinProject.output.value('boolean').mandatory();const issueAsset = app.addMutation('issueAsset', async (input: IssueAssetInput, current) => {const holder = await current.templates.employee.getItem(input.employeeId);const issued = await current.unions.asset.getItem(input.assetId);if (holder === undefined || issued === undefined) throw new Error('Employee or asset not found');const relation = holder.relations.assets;if (relation.type !== 'many') throw new Error('Expected a many-side Relation');return await relation.add(issued);});issueAsset.input.addProperty('employeeId', 'id').mandatory();issueAsset.input.addProperty('assetId', 'id').mandatory();issueAsset.output.value('boolean').mandatory();const deskOf = app.addQuery('deskOf', async (input: EmployeeInput, current) => {const occupant = await current.templates.employee.getItem(input.employeeId);const relation = occupant?.relations.desk;if (relation === undefined || relation.type !== 'one') return undefined;return (await relation.get())?.underlyingItem;});deskOf.input.addProperty('employeeId', 'id').mandatory();deskOf.output.item(desk);const reports = app.addQuery('reports', async (input: EmployeeInput, current: ReadAppInstance) => {const manager = await current.templates.employee.getItem(input.employeeId);const relation = manager?.relations.reports;if (relation === undefined || relation.type !== 'many') return [];const selected = await relation.select().execute();return selected.results.map((related) => related.underlyingItem);});reports.input.addProperty('employeeId', 'id').mandatory();reports.output.item(employee).array();const holderOf = app.addQuery('holderOf', async (input: AssetInput, current) => {const issued = await current.unions.asset.getItem(input.assetId);const relation = issued?.relations.holder;if (relation === undefined || relation.type !== 'one') return undefined;return (await relation.get())?.underlyingItem;});holderOf.input.addProperty('assetId', 'id').mandatory();holderOf.output.item(employee);}; -
Narrow the side you hold.
item.relations.<key>is a one-side instance when the other end holds at most one Item and a many-side instance otherwise; itstypeis'one'or'many'. Checktypebefore calling side-specific methods. Foremployee.relations.managerthe type is'one'; formanager.relations.reportsit is'many'.examples/relationships/staffing.ts import type { AppSpec } from '@alpynehq/alpyne-types/builder';import type { ReadAppInstance } from '@alpynehq/alpyne-types/runtime';interface AssignDeskInput {readonly deskId: string;readonly employeeId: string;}interface SetManagerInput {readonly employeeId: string;readonly managerId: string;}interface JoinProjectInput {readonly employeeId: string;readonly projectId: string;}interface IssueAssetInput {readonly assetId: string;readonly employeeId: string;}interface EmployeeInput {readonly employeeId: string;}interface AssetInput {readonly assetId: string;}export const staffApp: AppSpec = (app) => {app.configure('staffing');const employee = app.addTemplate('employee');employee.addProperty('name', 'string');const desk = app.addTemplate('desk');desk.addProperty('label', 'string');const laptop = app.addTemplate('laptop');laptop.addProperty('serial', 'string');const project = app.addTemplate('project');project.addProperty('name', 'string');const asset = app.addUnion('asset', [desk, laptop]);employee.addRelation('desk', 'one-to-one', desk, { toKey: 'occupant' });employee.addRelation('manager', 'many-to-one', employee, { toKey: 'reports' });project.addRelation('members', 'many-to-many', employee, { toKey: 'projects' });employee.addRelation('assets', 'one-to-many', asset, { toKey: 'holder' });const assignDesk = app.addMutation('assignDesk', async (input: AssignDeskInput, current) => {const occupant = await current.templates.employee.getItem(input.employeeId);const target = await current.templates.desk.getItem(input.deskId);if (occupant === undefined || target === undefined) throw new Error('Employee or desk not found');const relation = occupant.relations.desk;if (relation.type !== 'one') throw new Error('Expected a one-side Relation');return await relation.setIfNotExists(target);});assignDesk.input.addProperty('employeeId', 'id').mandatory();assignDesk.input.addProperty('deskId', 'id').mandatory();assignDesk.output.value('boolean').mandatory();const setManager = app.addMutation('setManager', async (input: SetManagerInput, current) => {const report = await current.templates.employee.getItem(input.employeeId);const manager = await current.templates.employee.getItem(input.managerId);if (report === undefined || manager === undefined) throw new Error('Employee not found');const relation = report.relations.manager;if (relation.type !== 'one') throw new Error('Expected a one-side Relation');await relation.set(manager);});setManager.input.addProperty('employeeId', 'id').mandatory();setManager.input.addProperty('managerId', 'id').mandatory();setManager.output.void();const joinProject = app.addMutation('joinProject', async (input: JoinProjectInput, current) => {const team = await current.templates.project.getItem(input.projectId);const member = await current.templates.employee.getItem(input.employeeId);if (team === undefined || member === undefined) throw new Error('Project or employee not found');const relation = team.relations.members;if (relation.type !== 'many') throw new Error('Expected a many-side Relation');return await relation.addIfNotExists(member);});joinProject.input.addProperty('projectId', 'id').mandatory();joinProject.input.addProperty('employeeId', 'id').mandatory();joinProject.output.value('boolean').mandatory();const issueAsset = app.addMutation('issueAsset', async (input: IssueAssetInput, current) => {const holder = await current.templates.employee.getItem(input.employeeId);const issued = await current.unions.asset.getItem(input.assetId);if (holder === undefined || issued === undefined) throw new Error('Employee or asset not found');const relation = holder.relations.assets;if (relation.type !== 'many') throw new Error('Expected a many-side Relation');return await relation.add(issued);});issueAsset.input.addProperty('employeeId', 'id').mandatory();issueAsset.input.addProperty('assetId', 'id').mandatory();issueAsset.output.value('boolean').mandatory();const deskOf = app.addQuery('deskOf', async (input: EmployeeInput, current) => {const occupant = await current.templates.employee.getItem(input.employeeId);const relation = occupant?.relations.desk;if (relation === undefined || relation.type !== 'one') return undefined;return (await relation.get())?.underlyingItem;});deskOf.input.addProperty('employeeId', 'id').mandatory();deskOf.output.item(desk);const reports = app.addQuery('reports', async (input: EmployeeInput, current: ReadAppInstance) => {const manager = await current.templates.employee.getItem(input.employeeId);const relation = manager?.relations.reports;if (relation === undefined || relation.type !== 'many') return [];const selected = await relation.select().execute();return selected.results.map((related) => related.underlyingItem);});reports.input.addProperty('employeeId', 'id').mandatory();reports.output.item(employee).array();const holderOf = app.addQuery('holderOf', async (input: AssetInput, current) => {const issued = await current.unions.asset.getItem(input.assetId);const relation = issued?.relations.holder;if (relation === undefined || relation.type !== 'one') return undefined;return (await relation.get())?.underlyingItem;});holderOf.input.addProperty('assetId', 'id').mandatory();holderOf.output.item(employee);}; -
Set a one-side target with
set(target). It replaces any existing target and resolvestrueonly when no target was set before.setIfNotExists(target, condition)leaves an existing target in place and resolvesfalse, so a Mutation that runs twice does not reassign the desk. The optional{ existingMaxAge }condition, in milliseconds, treats an older target as replaceable.clear()removes the target.examples/relationships/staffing.ts import type { AppSpec } from '@alpynehq/alpyne-types/builder';import type { ReadAppInstance } from '@alpynehq/alpyne-types/runtime';interface AssignDeskInput {readonly deskId: string;readonly employeeId: string;}interface SetManagerInput {readonly employeeId: string;readonly managerId: string;}interface JoinProjectInput {readonly employeeId: string;readonly projectId: string;}interface IssueAssetInput {readonly assetId: string;readonly employeeId: string;}interface EmployeeInput {readonly employeeId: string;}interface AssetInput {readonly assetId: string;}export const staffApp: AppSpec = (app) => {app.configure('staffing');const employee = app.addTemplate('employee');employee.addProperty('name', 'string');const desk = app.addTemplate('desk');desk.addProperty('label', 'string');const laptop = app.addTemplate('laptop');laptop.addProperty('serial', 'string');const project = app.addTemplate('project');project.addProperty('name', 'string');const asset = app.addUnion('asset', [desk, laptop]);employee.addRelation('desk', 'one-to-one', desk, { toKey: 'occupant' });employee.addRelation('manager', 'many-to-one', employee, { toKey: 'reports' });project.addRelation('members', 'many-to-many', employee, { toKey: 'projects' });employee.addRelation('assets', 'one-to-many', asset, { toKey: 'holder' });const assignDesk = app.addMutation('assignDesk', async (input: AssignDeskInput, current) => {const occupant = await current.templates.employee.getItem(input.employeeId);const target = await current.templates.desk.getItem(input.deskId);if (occupant === undefined || target === undefined) throw new Error('Employee or desk not found');const relation = occupant.relations.desk;if (relation.type !== 'one') throw new Error('Expected a one-side Relation');return await relation.setIfNotExists(target);});assignDesk.input.addProperty('employeeId', 'id').mandatory();assignDesk.input.addProperty('deskId', 'id').mandatory();assignDesk.output.value('boolean').mandatory();const setManager = app.addMutation('setManager', async (input: SetManagerInput, current) => {const report = await current.templates.employee.getItem(input.employeeId);const manager = await current.templates.employee.getItem(input.managerId);if (report === undefined || manager === undefined) throw new Error('Employee not found');const relation = report.relations.manager;if (relation.type !== 'one') throw new Error('Expected a one-side Relation');await relation.set(manager);});setManager.input.addProperty('employeeId', 'id').mandatory();setManager.input.addProperty('managerId', 'id').mandatory();setManager.output.void();const joinProject = app.addMutation('joinProject', async (input: JoinProjectInput, current) => {const team = await current.templates.project.getItem(input.projectId);const member = await current.templates.employee.getItem(input.employeeId);if (team === undefined || member === undefined) throw new Error('Project or employee not found');const relation = team.relations.members;if (relation.type !== 'many') throw new Error('Expected a many-side Relation');return await relation.addIfNotExists(member);});joinProject.input.addProperty('projectId', 'id').mandatory();joinProject.input.addProperty('employeeId', 'id').mandatory();joinProject.output.value('boolean').mandatory();const issueAsset = app.addMutation('issueAsset', async (input: IssueAssetInput, current) => {const holder = await current.templates.employee.getItem(input.employeeId);const issued = await current.unions.asset.getItem(input.assetId);if (holder === undefined || issued === undefined) throw new Error('Employee or asset not found');const relation = holder.relations.assets;if (relation.type !== 'many') throw new Error('Expected a many-side Relation');return await relation.add(issued);});issueAsset.input.addProperty('employeeId', 'id').mandatory();issueAsset.input.addProperty('assetId', 'id').mandatory();issueAsset.output.value('boolean').mandatory();const deskOf = app.addQuery('deskOf', async (input: EmployeeInput, current) => {const occupant = await current.templates.employee.getItem(input.employeeId);const relation = occupant?.relations.desk;if (relation === undefined || relation.type !== 'one') return undefined;return (await relation.get())?.underlyingItem;});deskOf.input.addProperty('employeeId', 'id').mandatory();deskOf.output.item(desk);const reports = app.addQuery('reports', async (input: EmployeeInput, current: ReadAppInstance) => {const manager = await current.templates.employee.getItem(input.employeeId);const relation = manager?.relations.reports;if (relation === undefined || relation.type !== 'many') return [];const selected = await relation.select().execute();return selected.results.map((related) => related.underlyingItem);});reports.input.addProperty('employeeId', 'id').mandatory();reports.output.item(employee).array();const holderOf = app.addQuery('holderOf', async (input: AssetInput, current) => {const issued = await current.unions.asset.getItem(input.assetId);const relation = issued?.relations.holder;if (relation === undefined || relation.type !== 'one') return undefined;return (await relation.get())?.underlyingItem;});holderOf.input.addProperty('assetId', 'id').mandatory();holderOf.output.item(employee);}; -
Add many-side targets with
add(target)oradd([targets]). Adding a target that is already present resolvesfalseand changes nothing.addIfNotExists(target, condition)makes that idempotency explicit and accepts the same age condition.remove(target)drops one target andclear()drops them all. Every target must belong to the Relation’s to-side Template or Union; the Runtime rejects any other Item.examples/relationships/staffing.ts import type { AppSpec } from '@alpynehq/alpyne-types/builder';import type { ReadAppInstance } from '@alpynehq/alpyne-types/runtime';interface AssignDeskInput {readonly deskId: string;readonly employeeId: string;}interface SetManagerInput {readonly employeeId: string;readonly managerId: string;}interface JoinProjectInput {readonly employeeId: string;readonly projectId: string;}interface IssueAssetInput {readonly assetId: string;readonly employeeId: string;}interface EmployeeInput {readonly employeeId: string;}interface AssetInput {readonly assetId: string;}export const staffApp: AppSpec = (app) => {app.configure('staffing');const employee = app.addTemplate('employee');employee.addProperty('name', 'string');const desk = app.addTemplate('desk');desk.addProperty('label', 'string');const laptop = app.addTemplate('laptop');laptop.addProperty('serial', 'string');const project = app.addTemplate('project');project.addProperty('name', 'string');const asset = app.addUnion('asset', [desk, laptop]);employee.addRelation('desk', 'one-to-one', desk, { toKey: 'occupant' });employee.addRelation('manager', 'many-to-one', employee, { toKey: 'reports' });project.addRelation('members', 'many-to-many', employee, { toKey: 'projects' });employee.addRelation('assets', 'one-to-many', asset, { toKey: 'holder' });const assignDesk = app.addMutation('assignDesk', async (input: AssignDeskInput, current) => {const occupant = await current.templates.employee.getItem(input.employeeId);const target = await current.templates.desk.getItem(input.deskId);if (occupant === undefined || target === undefined) throw new Error('Employee or desk not found');const relation = occupant.relations.desk;if (relation.type !== 'one') throw new Error('Expected a one-side Relation');return await relation.setIfNotExists(target);});assignDesk.input.addProperty('employeeId', 'id').mandatory();assignDesk.input.addProperty('deskId', 'id').mandatory();assignDesk.output.value('boolean').mandatory();const setManager = app.addMutation('setManager', async (input: SetManagerInput, current) => {const report = await current.templates.employee.getItem(input.employeeId);const manager = await current.templates.employee.getItem(input.managerId);if (report === undefined || manager === undefined) throw new Error('Employee not found');const relation = report.relations.manager;if (relation.type !== 'one') throw new Error('Expected a one-side Relation');await relation.set(manager);});setManager.input.addProperty('employeeId', 'id').mandatory();setManager.input.addProperty('managerId', 'id').mandatory();setManager.output.void();const joinProject = app.addMutation('joinProject', async (input: JoinProjectInput, current) => {const team = await current.templates.project.getItem(input.projectId);const member = await current.templates.employee.getItem(input.employeeId);if (team === undefined || member === undefined) throw new Error('Project or employee not found');const relation = team.relations.members;if (relation.type !== 'many') throw new Error('Expected a many-side Relation');return await relation.addIfNotExists(member);});joinProject.input.addProperty('projectId', 'id').mandatory();joinProject.input.addProperty('employeeId', 'id').mandatory();joinProject.output.value('boolean').mandatory();const issueAsset = app.addMutation('issueAsset', async (input: IssueAssetInput, current) => {const holder = await current.templates.employee.getItem(input.employeeId);const issued = await current.unions.asset.getItem(input.assetId);if (holder === undefined || issued === undefined) throw new Error('Employee or asset not found');const relation = holder.relations.assets;if (relation.type !== 'many') throw new Error('Expected a many-side Relation');return await relation.add(issued);});issueAsset.input.addProperty('employeeId', 'id').mandatory();issueAsset.input.addProperty('assetId', 'id').mandatory();issueAsset.output.value('boolean').mandatory();const deskOf = app.addQuery('deskOf', async (input: EmployeeInput, current) => {const occupant = await current.templates.employee.getItem(input.employeeId);const relation = occupant?.relations.desk;if (relation === undefined || relation.type !== 'one') return undefined;return (await relation.get())?.underlyingItem;});deskOf.input.addProperty('employeeId', 'id').mandatory();deskOf.output.item(desk);const reports = app.addQuery('reports', async (input: EmployeeInput, current: ReadAppInstance) => {const manager = await current.templates.employee.getItem(input.employeeId);const relation = manager?.relations.reports;if (relation === undefined || relation.type !== 'many') return [];const selected = await relation.select().execute();return selected.results.map((related) => related.underlyingItem);});reports.input.addProperty('employeeId', 'id').mandatory();reports.output.item(employee).array();const holderOf = app.addQuery('holderOf', async (input: AssetInput, current) => {const issued = await current.unions.asset.getItem(input.assetId);const relation = issued?.relations.holder;if (relation === undefined || relation.type !== 'one') return undefined;return (await relation.get())?.underlyingItem;});holderOf.input.addProperty('assetId', 'id').mandatory();holderOf.output.item(employee);}; -
Navigate a one side with
get(). It resolves the target as aRelatedItemorundefined. ARelatedItemis the target Item plus arelationblock withcreatedAt,fromId,toIdandrelationPrn. ReadunderlyingItemwhen you pass the target on, for example as a parent tocreateChildor into anotherset.examples/relationships/staffing.ts import type { AppSpec } from '@alpynehq/alpyne-types/builder';import type { ReadAppInstance } from '@alpynehq/alpyne-types/runtime';interface AssignDeskInput {readonly deskId: string;readonly employeeId: string;}interface SetManagerInput {readonly employeeId: string;readonly managerId: string;}interface JoinProjectInput {readonly employeeId: string;readonly projectId: string;}interface IssueAssetInput {readonly assetId: string;readonly employeeId: string;}interface EmployeeInput {readonly employeeId: string;}interface AssetInput {readonly assetId: string;}export const staffApp: AppSpec = (app) => {app.configure('staffing');const employee = app.addTemplate('employee');employee.addProperty('name', 'string');const desk = app.addTemplate('desk');desk.addProperty('label', 'string');const laptop = app.addTemplate('laptop');laptop.addProperty('serial', 'string');const project = app.addTemplate('project');project.addProperty('name', 'string');const asset = app.addUnion('asset', [desk, laptop]);employee.addRelation('desk', 'one-to-one', desk, { toKey: 'occupant' });employee.addRelation('manager', 'many-to-one', employee, { toKey: 'reports' });project.addRelation('members', 'many-to-many', employee, { toKey: 'projects' });employee.addRelation('assets', 'one-to-many', asset, { toKey: 'holder' });const assignDesk = app.addMutation('assignDesk', async (input: AssignDeskInput, current) => {const occupant = await current.templates.employee.getItem(input.employeeId);const target = await current.templates.desk.getItem(input.deskId);if (occupant === undefined || target === undefined) throw new Error('Employee or desk not found');const relation = occupant.relations.desk;if (relation.type !== 'one') throw new Error('Expected a one-side Relation');return await relation.setIfNotExists(target);});assignDesk.input.addProperty('employeeId', 'id').mandatory();assignDesk.input.addProperty('deskId', 'id').mandatory();assignDesk.output.value('boolean').mandatory();const setManager = app.addMutation('setManager', async (input: SetManagerInput, current) => {const report = await current.templates.employee.getItem(input.employeeId);const manager = await current.templates.employee.getItem(input.managerId);if (report === undefined || manager === undefined) throw new Error('Employee not found');const relation = report.relations.manager;if (relation.type !== 'one') throw new Error('Expected a one-side Relation');await relation.set(manager);});setManager.input.addProperty('employeeId', 'id').mandatory();setManager.input.addProperty('managerId', 'id').mandatory();setManager.output.void();const joinProject = app.addMutation('joinProject', async (input: JoinProjectInput, current) => {const team = await current.templates.project.getItem(input.projectId);const member = await current.templates.employee.getItem(input.employeeId);if (team === undefined || member === undefined) throw new Error('Project or employee not found');const relation = team.relations.members;if (relation.type !== 'many') throw new Error('Expected a many-side Relation');return await relation.addIfNotExists(member);});joinProject.input.addProperty('projectId', 'id').mandatory();joinProject.input.addProperty('employeeId', 'id').mandatory();joinProject.output.value('boolean').mandatory();const issueAsset = app.addMutation('issueAsset', async (input: IssueAssetInput, current) => {const holder = await current.templates.employee.getItem(input.employeeId);const issued = await current.unions.asset.getItem(input.assetId);if (holder === undefined || issued === undefined) throw new Error('Employee or asset not found');const relation = holder.relations.assets;if (relation.type !== 'many') throw new Error('Expected a many-side Relation');return await relation.add(issued);});issueAsset.input.addProperty('employeeId', 'id').mandatory();issueAsset.input.addProperty('assetId', 'id').mandatory();issueAsset.output.value('boolean').mandatory();const deskOf = app.addQuery('deskOf', async (input: EmployeeInput, current) => {const occupant = await current.templates.employee.getItem(input.employeeId);const relation = occupant?.relations.desk;if (relation === undefined || relation.type !== 'one') return undefined;return (await relation.get())?.underlyingItem;});deskOf.input.addProperty('employeeId', 'id').mandatory();deskOf.output.item(desk);const reports = app.addQuery('reports', async (input: EmployeeInput, current: ReadAppInstance) => {const manager = await current.templates.employee.getItem(input.employeeId);const relation = manager?.relations.reports;if (relation === undefined || relation.type !== 'many') return [];const selected = await relation.select().execute();return selected.results.map((related) => related.underlyingItem);});reports.input.addProperty('employeeId', 'id').mandatory();reports.output.item(employee).array();const holderOf = app.addQuery('holderOf', async (input: AssetInput, current) => {const issued = await current.unions.asset.getItem(input.assetId);const relation = issued?.relations.holder;if (relation === undefined || relation.type !== 'one') return undefined;return (await relation.get())?.underlyingItem;});holderOf.input.addProperty('assetId', 'id').mandatory();holderOf.output.item(employee);}; -
Navigate a many side with
select(). It returns a selector over the targets, solimit,cursor,paginate,sortandarchivedapply. Awaitexecute()for theresults, orfirst()for one target. Each result is aRelatedItemcarrying its ownrelationmetadata.examples/relationships/staffing.ts import type { AppSpec } from '@alpynehq/alpyne-types/builder';import type { ReadAppInstance } from '@alpynehq/alpyne-types/runtime';interface AssignDeskInput {readonly deskId: string;readonly employeeId: string;}interface SetManagerInput {readonly employeeId: string;readonly managerId: string;}interface JoinProjectInput {readonly employeeId: string;readonly projectId: string;}interface IssueAssetInput {readonly assetId: string;readonly employeeId: string;}interface EmployeeInput {readonly employeeId: string;}interface AssetInput {readonly assetId: string;}export const staffApp: AppSpec = (app) => {app.configure('staffing');const employee = app.addTemplate('employee');employee.addProperty('name', 'string');const desk = app.addTemplate('desk');desk.addProperty('label', 'string');const laptop = app.addTemplate('laptop');laptop.addProperty('serial', 'string');const project = app.addTemplate('project');project.addProperty('name', 'string');const asset = app.addUnion('asset', [desk, laptop]);employee.addRelation('desk', 'one-to-one', desk, { toKey: 'occupant' });employee.addRelation('manager', 'many-to-one', employee, { toKey: 'reports' });project.addRelation('members', 'many-to-many', employee, { toKey: 'projects' });employee.addRelation('assets', 'one-to-many', asset, { toKey: 'holder' });const assignDesk = app.addMutation('assignDesk', async (input: AssignDeskInput, current) => {const occupant = await current.templates.employee.getItem(input.employeeId);const target = await current.templates.desk.getItem(input.deskId);if (occupant === undefined || target === undefined) throw new Error('Employee or desk not found');const relation = occupant.relations.desk;if (relation.type !== 'one') throw new Error('Expected a one-side Relation');return await relation.setIfNotExists(target);});assignDesk.input.addProperty('employeeId', 'id').mandatory();assignDesk.input.addProperty('deskId', 'id').mandatory();assignDesk.output.value('boolean').mandatory();const setManager = app.addMutation('setManager', async (input: SetManagerInput, current) => {const report = await current.templates.employee.getItem(input.employeeId);const manager = await current.templates.employee.getItem(input.managerId);if (report === undefined || manager === undefined) throw new Error('Employee not found');const relation = report.relations.manager;if (relation.type !== 'one') throw new Error('Expected a one-side Relation');await relation.set(manager);});setManager.input.addProperty('employeeId', 'id').mandatory();setManager.input.addProperty('managerId', 'id').mandatory();setManager.output.void();const joinProject = app.addMutation('joinProject', async (input: JoinProjectInput, current) => {const team = await current.templates.project.getItem(input.projectId);const member = await current.templates.employee.getItem(input.employeeId);if (team === undefined || member === undefined) throw new Error('Project or employee not found');const relation = team.relations.members;if (relation.type !== 'many') throw new Error('Expected a many-side Relation');return await relation.addIfNotExists(member);});joinProject.input.addProperty('projectId', 'id').mandatory();joinProject.input.addProperty('employeeId', 'id').mandatory();joinProject.output.value('boolean').mandatory();const issueAsset = app.addMutation('issueAsset', async (input: IssueAssetInput, current) => {const holder = await current.templates.employee.getItem(input.employeeId);const issued = await current.unions.asset.getItem(input.assetId);if (holder === undefined || issued === undefined) throw new Error('Employee or asset not found');const relation = holder.relations.assets;if (relation.type !== 'many') throw new Error('Expected a many-side Relation');return await relation.add(issued);});issueAsset.input.addProperty('employeeId', 'id').mandatory();issueAsset.input.addProperty('assetId', 'id').mandatory();issueAsset.output.value('boolean').mandatory();const deskOf = app.addQuery('deskOf', async (input: EmployeeInput, current) => {const occupant = await current.templates.employee.getItem(input.employeeId);const relation = occupant?.relations.desk;if (relation === undefined || relation.type !== 'one') return undefined;return (await relation.get())?.underlyingItem;});deskOf.input.addProperty('employeeId', 'id').mandatory();deskOf.output.item(desk);const reports = app.addQuery('reports', async (input: EmployeeInput, current: ReadAppInstance) => {const manager = await current.templates.employee.getItem(input.employeeId);const relation = manager?.relations.reports;if (relation === undefined || relation.type !== 'many') return [];const selected = await relation.select().execute();return selected.results.map((related) => related.underlyingItem);});reports.input.addProperty('employeeId', 'id').mandatory();reports.output.item(employee).array();const holderOf = app.addQuery('holderOf', async (input: AssetInput, current) => {const issued = await current.unions.asset.getItem(input.assetId);const relation = issued?.relations.holder;if (relation === undefined || relation.type !== 'one') return undefined;return (await relation.get())?.underlyingItem;});holderOf.input.addProperty('assetId', 'id').mandatory();holderOf.output.item(employee);}; -
Target a Union to accept several Templates.
employee.relations.assetsaccepts a desk or a laptop becauseassetis a Union of both. Look the target up throughcurrent.unions.asset.getItem(id), and navigate back from either member Template through the Relation’stoKey.examples/relationships/staffing.ts import type { AppSpec } from '@alpynehq/alpyne-types/builder';import type { ReadAppInstance } from '@alpynehq/alpyne-types/runtime';interface AssignDeskInput {readonly deskId: string;readonly employeeId: string;}interface SetManagerInput {readonly employeeId: string;readonly managerId: string;}interface JoinProjectInput {readonly employeeId: string;readonly projectId: string;}interface IssueAssetInput {readonly assetId: string;readonly employeeId: string;}interface EmployeeInput {readonly employeeId: string;}interface AssetInput {readonly assetId: string;}export const staffApp: AppSpec = (app) => {app.configure('staffing');const employee = app.addTemplate('employee');employee.addProperty('name', 'string');const desk = app.addTemplate('desk');desk.addProperty('label', 'string');const laptop = app.addTemplate('laptop');laptop.addProperty('serial', 'string');const project = app.addTemplate('project');project.addProperty('name', 'string');const asset = app.addUnion('asset', [desk, laptop]);employee.addRelation('desk', 'one-to-one', desk, { toKey: 'occupant' });employee.addRelation('manager', 'many-to-one', employee, { toKey: 'reports' });project.addRelation('members', 'many-to-many', employee, { toKey: 'projects' });employee.addRelation('assets', 'one-to-many', asset, { toKey: 'holder' });const assignDesk = app.addMutation('assignDesk', async (input: AssignDeskInput, current) => {const occupant = await current.templates.employee.getItem(input.employeeId);const target = await current.templates.desk.getItem(input.deskId);if (occupant === undefined || target === undefined) throw new Error('Employee or desk not found');const relation = occupant.relations.desk;if (relation.type !== 'one') throw new Error('Expected a one-side Relation');return await relation.setIfNotExists(target);});assignDesk.input.addProperty('employeeId', 'id').mandatory();assignDesk.input.addProperty('deskId', 'id').mandatory();assignDesk.output.value('boolean').mandatory();const setManager = app.addMutation('setManager', async (input: SetManagerInput, current) => {const report = await current.templates.employee.getItem(input.employeeId);const manager = await current.templates.employee.getItem(input.managerId);if (report === undefined || manager === undefined) throw new Error('Employee not found');const relation = report.relations.manager;if (relation.type !== 'one') throw new Error('Expected a one-side Relation');await relation.set(manager);});setManager.input.addProperty('employeeId', 'id').mandatory();setManager.input.addProperty('managerId', 'id').mandatory();setManager.output.void();const joinProject = app.addMutation('joinProject', async (input: JoinProjectInput, current) => {const team = await current.templates.project.getItem(input.projectId);const member = await current.templates.employee.getItem(input.employeeId);if (team === undefined || member === undefined) throw new Error('Project or employee not found');const relation = team.relations.members;if (relation.type !== 'many') throw new Error('Expected a many-side Relation');return await relation.addIfNotExists(member);});joinProject.input.addProperty('projectId', 'id').mandatory();joinProject.input.addProperty('employeeId', 'id').mandatory();joinProject.output.value('boolean').mandatory();const issueAsset = app.addMutation('issueAsset', async (input: IssueAssetInput, current) => {const holder = await current.templates.employee.getItem(input.employeeId);const issued = await current.unions.asset.getItem(input.assetId);if (holder === undefined || issued === undefined) throw new Error('Employee or asset not found');const relation = holder.relations.assets;if (relation.type !== 'many') throw new Error('Expected a many-side Relation');return await relation.add(issued);});issueAsset.input.addProperty('employeeId', 'id').mandatory();issueAsset.input.addProperty('assetId', 'id').mandatory();issueAsset.output.value('boolean').mandatory();const deskOf = app.addQuery('deskOf', async (input: EmployeeInput, current) => {const occupant = await current.templates.employee.getItem(input.employeeId);const relation = occupant?.relations.desk;if (relation === undefined || relation.type !== 'one') return undefined;return (await relation.get())?.underlyingItem;});deskOf.input.addProperty('employeeId', 'id').mandatory();deskOf.output.item(desk);const reports = app.addQuery('reports', async (input: EmployeeInput, current: ReadAppInstance) => {const manager = await current.templates.employee.getItem(input.employeeId);const relation = manager?.relations.reports;if (relation === undefined || relation.type !== 'many') return [];const selected = await relation.select().execute();return selected.results.map((related) => related.underlyingItem);});reports.input.addProperty('employeeId', 'id').mandatory();reports.output.item(employee).array();const holderOf = app.addQuery('holderOf', async (input: AssetInput, current) => {const issued = await current.unions.asset.getItem(input.assetId);const relation = issued?.relations.holder;if (relation === undefined || relation.type !== 'one') return undefined;return (await relation.get())?.underlyingItem;});holderOf.input.addProperty('assetId', 'id').mandatory();holderOf.output.item(employee);};
Verify
Section titled “Verify”The test below assigns a desk twice, sets a manager, joins a project twice, issues two kinds of asset, and reads every Relation back from both sides.
import type { ReadItem } from '@alpynehq/alpyne-types/runtime';import { createHarnessInstance } from '@pyn-backend/platform-harness-public';import { createTestPlatformService } from '@pyn-backend/platform-service-test';import { createTestCronService } from '@pyn-backend/service-cron-test';import { createTestSystemService } from '@pyn-backend/service-system-test';import { createTestLoggerService } from '@pyn-backend/test-services-logger';import { describe, expect, it } from 'vitest';
import { staffApp } from './staffing';
describe('relate items', () => { it('sets, adds and navigates Relations of every cardinality', async () => { const system = createTestSystemService(); const logger = createTestLoggerService(); const cron = createTestCronService({ system }); const platform = createTestPlatformService({ cron, logger, system }); const harness = await createHarnessInstance({ cron, logger, platform, system }, staffApp); const workspace = await harness.createWorkspace();
// The harness runs every execution as system. const ids = await workspace.write(async (ctx) => { const { desk, employee, laptop, project } = ctx.apps.staffing.templates; const root = await ctx.getWorkspaceItem(); const manager = await root.createChild(employee, { properties: { name: 'Grace' } }); const report = await root.createChild(employee, { properties: { name: 'Linus' } }); const corner = await root.createChild(desk, { properties: { label: 'Corner' } }); const window = await root.createChild(desk, { properties: { label: 'Window' } }); const machine = await root.createChild(laptop, { properties: { serial: 'X1' } }); const launch = await root.createChild(project, { properties: { name: 'Launch' } }); return { corner: corner.id, launch: launch.id, machine: machine.id, manager: manager.id, report: report.id, window: window.id }; });
await workspace.write(async (ctx) => { const current = ctx.apps.staffing; const { assignDesk, issueAsset, joinProject, setManager } = current.mutations; expect(await assignDesk.handler({ deskId: ids.corner, employeeId: ids.report }, current, ctx)).toBe(true); expect(await assignDesk.handler({ deskId: ids.window, employeeId: ids.report }, current, ctx)).toBe(false); await setManager.handler({ employeeId: ids.report, managerId: ids.manager }, current, ctx); expect(await joinProject.handler({ employeeId: ids.report, projectId: ids.launch }, current, ctx)).toBe(true); expect(await joinProject.handler({ employeeId: ids.report, projectId: ids.launch }, current, ctx)).toBe(false); expect(await issueAsset.handler({ assetId: ids.corner, employeeId: ids.report }, current, ctx)).toBe(true); expect(await issueAsset.handler({ assetId: ids.machine, employeeId: ids.report }, current, ctx)).toBe(true); });
await workspace.read(async (ctx) => { const current = ctx.apps.staffing; const { deskOf, holderOf, reports } = current.queries; expect((await deskOf.handler({ employeeId: ids.report }, current, ctx))?.properties.label).toBe('Corner'); expect((await reports.handler({ employeeId: ids.manager }, current, ctx)).map((item: ReadItem) => item.id)).toStrictEqual([ids.report]); expect((await holderOf.handler({ assetId: ids.machine }, current, ctx))?.id).toBe(ids.report);
const report = await current.templates.employee.getItem(ids.report); const assets = report?.relations.assets; if (assets === undefined || assets.type !== 'many') throw new Error('Expected a many-side Relation'); const issued = await assets.select().execute(); expect(issued.results.map((related) => related.templatePrn).sort()).toStrictEqual([ 'prn::staffing:template/desk', 'prn::staffing:template/laptop', ]); expect(issued.results[0]?.relation.fromId).toBe(ids.report); }); expect.assertions(11); });});From the repository root, run:
pnpm run cli test alpynehq/alpyne/website/examples/relationships/You should see:
Test Files 1 passed (1) Tests 1 passed (1)The second assignDesk and joinProject calls resolve false because the link already exists. reports lists the employee from the manager’s side, holderOf navigates from a Union member back to the employee, and the selected assets carry relation.fromId.
Options
Section titled “Options”addRelation(...).evented()declares an Event on the from-side Template that the Runtime publishes withaction,otherIdandrelationPrnwhenever the Relation is set, added, removed or cleared.relation.isType(item)reports whether an Item belongs to the other end of the Relation, for narrowing beforesetoradd.
Related
Section titled “Related”- Data model for Relations, Unions and how they differ from the hierarchy.
- Define data for declaring the Templates on either end and placing Items in the hierarchy.
- Data and identity for the storage rules Relations follow in every Runtime.
- Unit of Work for how
setIfNotExistsandaddIfNotExistsbehave under concurrent writes. RelationBuilder,WriteOneRelationInstanceandWriteManyRelationInstancefor every method on each side.

