Skip to content

Relations, references and mapped fields: model and API

Section titled “Relations, references and mapped fields: model and API”

This page is for integrators and developers who read or write relation definitions, traverse related entries through the API, or need the exact rules behind reference fields, mapped fields and navigation links.

This page covers the distinct — but easily confused — mechanisms OSOS uses to link data across entities, all owned by the data-service:

  1. Data relations (DataRelation) — first-class, queryable definitions of how one entity relates to another. They power the “related entries” tabs, sub-lists, the entity Joiner, and relation-sourced reactions.
  2. Reference fields — Entity-typed fields on an entity that hold the actual pointer to a referenced entry (the source / sources configuration).
  3. Mapped fields — fields whose value is copied or synced from a referenced entry, governed by an update-mode policy.

It also documents navigation links (LinksService) — the sidebar link tree and shareable system links — because that area shares the “links & references” vocabulary.

All entity/entry-scoped endpoints below are mounted on DataRelationController, which requires the Auth2 authentication strategy and runs the entityVoter authorization voter for every operation.

ConceptWhere it livesWhat it storesDirection
Data relation (incoming)DataRelation documentExplicit definition owned by dataEntity, pointing at a targetField on targetEntityIncoming (relationType = 1)
Data relation (outgoing)Derived at read time from the entity’s own reference fieldsSynthetic, never persistedOutgoing (relationType = 0)
Reference fieldDataEntityField with dataType = Entity and a source/sourcesThe referenced entity + query used to pick an entryn/a (field-level)
Mapped fieldDataEntity.dataSources[] + field-level mappingfromFieldId → toFieldId value copy with an updateModen/a (value sync)
Navigation linkLinkDataEntry (link entity)Sidebar node pointing at a module/view/page/reportn/a

Before the model details, it helps to see the two everyday ways an administrator connects entities in the product:

  1. Reference field — a field of data type Entity on entity A that points to entries of entity B. Internally the reference is stored as a universal pointer, ReferenceProperty, a { dataEntity, dataEntry } pair (entity id + entry id), usually accompanied by a _resolved block carrying the related entry’s display title. Storing the pointer rather than plain text keeps the link stable even if the target entry’s display title later changes.
  2. Data relation — a first-class, named relationship between two entities (incoming/outgoing), managed from the Relations tab of the entity. Relations let you traverse related entries, show them as sub-lists, build Joiner virtual entities, and drive relation-sourced reactions.

Data relations are also what let you build nested, hierarchical organizational structures: an entity representing an organization can act as the parent of child entities representing its departments or projects, so data is organized according to the parent–child hierarchy between them.

A DataRelation is a document in the data-service. It extends Identified<UUID> and implements the shared IDataRelation interface.

FieldTypeRequiredNotes
idUUID(server)Primary key.
specificationVersionnumberyesDefaults to 1.
dataEntityUUIDyesThe entity that owns this relation definition.
nameLocalizedValueyesDisplay name; validated by LanguagesService.validateName.
descriptionNullableLocalizedValueno
iconIconyes
targetEntityUUIDyesThe entity on the other end.
targetFieldstringyesfullNormalizedName of the reference field that realizes the link (see below for which side it lives on).
relationTypeDataRelationTypeEnumyesOutgoing = 0, Incoming = 1.
normalizedNamestring(auto)Machine name, unique per dataEntity. Pattern-validated (NormalizedNameValidation). Since 1.6
isImplicitbooleannoDefaults to false. Implicit relations are read-only (see below).
updateIdentifierstringyesOptimistic-concurrency token (a UUID). Since 1.6

The NewDataRelation request body for create excludes id and updateIdentifier (both are server-assigned); the PATCH body excludes only id.

This is the single most important thing to understand:

  • Incoming relations are the stored DataRelation documents. They describe entries in targetEntity that point into dataEntity via a reference field named by targetField (that field lives on targetEntity). In the product, an incoming relation is one where the current entity acts as the “parent” entity, defined and modified by an administrator from the Relations tab.
  • Outgoing relations are computed on the fly from dataEntity’s own reference fields (getEntityRelationFieldsWithoutADT()), never persisted. Each of the entity’s reference fields yields one; their synthetic id is a composite key (see below) and their targetField is the fullNormalizedName of a field on dataEntity itself. In the product, an outgoing relation is one where the current entity acts as the “child.”

transformToRelationDto reflects this asymmetry: for an incoming relation it resolves the field on the related (target) entity; for an outgoing relation it resolves the field on the owning entity.

The V2 list/count endpoints return both buckets. For example findV2 builds outgoingRelations by walking each relation field’s sources[] (or the legacy single source) and emitting one synthetic DataRelation per source with id = "{dataEntity.id}:{field.id}:{source.entity}".

In the product, both incoming (inbound) and outgoing (outbound) relations are viewed from the entity’s Relations tab, each shown as a card carrying the relation’s name, icon, related entity, and relation field. Clicking a card opens a form with the relation’s details; entering new values and clicking Finish saves the change. To remove a relation, click the delete icon next to it: a confirmation prompt appears, and once confirmed the relation is permanently deleted and cannot be undone.

A relation with isImplicit = true is system-managed and locked:

  • PATCH throws ImplicitRelationUpdateException (IMPLICIT_UPDATE_RESTRICTION).
  • DELETE throws ImplicitRelationDeleteException (IMPLICIT_DELETE_RESTRICTION).

System-wide list/count endpoints hide implicit relations unless you opt in. applyImplicitFilter / applyImplicitWhere merge an isImplicit: false constraint using an explicit {and: [...]} conjunction (so a caller’s nested or cannot leak implicit rows) whenever the includeImplicit query flag is false (the default). Since 1.8

Example: the “Themes” incoming relation on the Application Shell Since 1.10

Section titled “Example: the “Themes” incoming relation on the Application Shell Since 1.10”

The core Application Shell entity (SHELL) shows the incoming-relation pattern above in a system-managed form. Data-service migration 1.10.0-a28 creates the implicit relation SHELL_THEMES_RELATION on it:

PropertyValue
dataEntitySHELL
targetEntity / targetFieldTHEME / shell
relationTypeIncoming
normalizedNamethemes
name“Themes” / “السمات” — “Themes that use this application shell”
isImplicittrue

The Application Shell has no outgoing field to themes: the relation simply lists the THEME entries whose shell reference field points at the shell entry. Because it is implicit it cannot be edited or deleted through the Relations API, and it is hidden from system-wide listings unless you pass includeImplicit=true. The migration writes the relation directly, so no DataRelationCreatedEvent is published for it.

An Application Shell entry is stored layout data that a theme can point at. The 1.10 web client does not render it, and no shell builder is part of 1.10.

On create, if the client supplies normalizedName it must be unique within the owning entity (DataRelationNormalizedNameDuplicateException / DATA_RELATION_NORMALIZED_NAME_DUPLICATE); otherwise it is auto-derived from name via generateUniqueNormalizedName(name, existingNames, 'relation'). The uniqueness check runs against all sibling relations of the same dataEntity.

updateIdentifier is an optimistic-lock token. On create it is set to a fresh v4(). On update, if the client sends an updateIdentifier that differs from the stored one, the write is rejected with UpdateIdentifierConflictException; otherwise the server rotates it to a new UUID. Since 1.6

All routes below are on DataRelationController. {entity} accepts an entity id or normalized name in its space (getEntityByIdOrNormalizedNameInSpace).

Method & pathHandlerPurpose
POST /v1/entities/{entity}/relationcreateCreate a relation for {entity}. Publishes DataRelationCreatedEvent.
GET /v1/entities/{entity}/relationfindList stored (incoming) relations of {entity} as DataRelationDto[].
GET /v2/entities/{entity}/relationfindV2Return {incoming, outgoing} (DataRelationListDto).
GET /v1/entities/{entity}/relation/countcountCount stored relations (optional where).
GET /v2/entities/{entity}/relation/countcountV2{incoming, outgoing} counts (DataRelationCountDto).
GET /v1/entities/{entity}/relation/{id}findByIdOne relation of {entity} as DataRelationDto.
GET /v1/relationsfindAllSystem-wide list. includeImplicit (default false); limit clamped to [1, 500], default 100.
GET /v1/relations/{id}findOneByIdOne relation by id (supports composite ids).
GET /v1/relations/countcountAllSystem-wide count. includeImplicit (default false).
POST /v1/entities/joiner/relationsfindEntitiesRelationsGiven {dataEntities: string[]}, return the union of their incoming relations.
GET /v1/entities/target/{targetEntity}/relationfindRelationsByTargetEntityUndocumented, system-service only. Returns [{relationId, targetField}].
PATCH /v1/entities/{entity}/relation/{id}updateByIdUpdate (blocked for implicit). Publishes DataRelationUpdatedEvent with a raw diff.
DELETE /v1/entities/{entity}/relation/{id}deleteByIdDelete (blocked for implicit). Publishes DataRelationDeletedEvent.

Given an entity, an entry, and a relation, these return (or count) the entries on the other end. Internally each resolves the relation, loads the targetEntity, and delegates to DataEntryService factories with a relation context of {targetField, entityId, entryId, relationType}.

Method & pathHandlerExtra inputs
GET /v1/entities/{entity}/entries/{entryId}/relations/{relationId}findRelatedEntriesfilter, include_virtual
GET /v2/.../relations/{relationId}findRelatedEntriesV2filterCriteria, search, include_virtual
GET /v3/.../relations/{relationId}findRelatedEntriesV3+ appliedQuickFilters, appliedTagsFilters → {entries, tags}
GET /v1/.../relations/{relationId}/kanban/{categoryFieldId}findRelatedEntriesKanbanViewgrouped board + categoryId, tags/quick filters
GET /v1/.../relations/{relationId}/countfindRelatedEntriesCountwhere, include_virtual
GET /v2/.../relations/{relationId}/countfindRelatedEntriesCountV2whereCriteria, search

The V3 route accepts appliedTagsFilters, whose tag criteria are resolved through TagsService.getTagsFilterCriteria(targetEntity.getId(), appliedTagsFilters) before being applied.

relationId is polymorphic. DataRelationRepository.findRelationById accepts:

  • A plain UUID — resolved with findById.
  • {entityId}:{fieldId}:{sourceEntityId} (3 parts) — resolves the relation field fieldId on entityId, verifies sourceEntityId exists in the field’s sources[] (or matches the legacy single source), and synthesizes an outgoing relation with targetEntity = sourceEntityId and targetField = field.fullNormalizedName. Unknown field or source → RelationNotExistException (RELATION_NOT_EXIST).
  • {entityId}:{fieldId} (2 parts) — same, using the field’s legacy source as targetEntity.

This is why the kanban and related-entries routes work for outgoing relations that have no stored DataRelation document.

POST /v1/entities/orders/relation
Content-Type: application/json
{
"specificationVersion": 1,
"dataEntity": "…orders-entity-id…",
"name": { "en": "Line items", "ar": "…" },
"icon": { … },
"targetEntity": "…order-lines-entity-id…",
"targetField": "order", // field on order-lines that points back to orders
"relationType": 1 // Incoming
// normalizedName optional; updateIdentifier must be omitted
}

Relation mutations publish domain events on the service bus (correlationId = traceId, plus sticky attributes for userId, delegateeId, delegationId, spaceId):

  • DataRelationCreatedEvent(relation, userId)
  • DataRelationUpdatedEvent(updatedRelation, userId, rawDiff) — rawDiff computed with just-diff between the pre- and post-update documents.
  • DataRelationDeletedEvent(relation, userId)

A reference field is a DataEntityField with dataType = Entity that carries a source. getEntityRelationFieldsWithoutADT() selects them: dataType === Entity, has source or a non-empty sources[], is not a virtual field, and its source is not an ADT (audit) entity.

  • source?: UUID — deprecated single source entity id. Still honored across the code (the composite-id 2-part form and the “single source (legacy)” branch in findV2).
  • sources?: FieldSources[] — the current model. Each FieldSources entry:
PropertyMeaning
entitySource entity id the field references.
entriesSourceOptional query id used to populate the picker (nullable).
entriesSourceParametersParameters bound to a parameterized entriesSource.
entriesSourceDependenciesFull normalized names of fields the query expressions depend on (computed by the backend to know when to refresh the dropdown).
relatedToIf non-null, the parent field’s fullNormalizedName this field cascades from.
relationThe DataRelation id used for cascaded entries (only meaningful when relatedTo is set).

When an administrator configures a reference field, they set:

  • The source that supplies the selectable options: a store, collection, query, or an entity/view/module.
  • Single vs. multiple selection, and tree vs. flat selectors.
  • Context filter pointers (such as Me, My groups, My roles, My org unit) to scope the options to the current user.
  • Cascaded-parent filtering — a reference field’s options can be constrained by the value of another reference field on the same entry (this is what relatedTo and relation above express).
  • Circular-relation denial — the platform prevents circular relations that could cause infinite references.
  • Resync — a reference field can declare fields whose change recalculates it (resyncFields), with a preserve value on edit option (preserveValueOnEdit) to keep the recalculated value rather than overwrite it.
  • A collection reference always shows its resolved main title in view mode. A reference that points at a data collection rather than an entity carries only an id plus a resolved main title, so there is no mainTitleField to derive from it. View mode renders the main title regardless, so the value is displayed instead of coming out blank.
  • Search-picked values survive a dropdown reload. Reference pickers are backed by server-side search, so the option list only ever holds the current page of results. A field that holds multiple values keeps every id the user has already selected, even after the dropdown reloads its options for a different search term — the selection, not the visible page, is authoritative, and deselecting an id still removes it.
  • An unresolved single value normalizes to empty. On a single-value reference field, an id that resolves to no payload settles as an explicit empty value rather than lingering as a broken reference or propagating an undefined one.

Mapped fields copy values from a referenced entry into the current entity when an entry is created or updated. This is implemented by MappingFieldService.

The update modes appear in the field settings as Local Update (Local), Never (Never), From Parent Only (ParentOnly) and 2 way (TwoWay). In the form, a mapped field in Never or From Parent Only mode is read-only; 2 way is offered only when the mapped field’s required setting matches its source field’s, and a mapped field inside a repeatable block that differs from its reference field’s block can only use Never or From Parent Only.

Three pieces of config drive mapping:

  1. Entity-level dataSources: DataEntityFieldSources[] — each source is { referenceEntity, referenceField, mappedFields: MappingFields[] }. referenceField is the id of the reference field on this entity whose selected entry supplies the values.
  2. Per-mapping MappingFields — { fromFieldId, toFieldId, updateMode }, where fromFieldId is a field on the referenced entity and toFieldId a field on this entity.
  3. Field-level mapping: DataEntityFieldMapping — { enabled, referenceFieldId, sourceFieldId, updateMode, searchMode }. A target field is only written if mapping.enabled is true. searchMode (MappedFieldSearchModeEnum: None, Full, StartsWith, Partial) controls how the mapped value participates in search.

MappedFieldUpdateModeEnum decides who wins when the source and local values disagree. Behavior is implemented in handleMappingFields:

ModeValueEffective behavior
Local0Keep the local value unless the reference changed (isReferenceChanged); on a reference change, pull the source value. Preserves local edits between reference changes.
Never1Keep the local value whenever it is defined (or when there is no source field); otherwise seed from source. Existing local values are never overwritten.
ParentOnly2Falls through to the default branch: always take the source (fromFieldValue). Source is authoritative.
TwoWay3If the reference changed and the caller did not set childToParentHighPriority, take the source; otherwise keep the local (child) value. Lets a child edit propagate back toward the parent. Since 1.6

isReferenceChanged compares the referenced entry id currently stored on the entry against the incoming sourceEntryId. In the entity-wide pass (getValuesByEntityDataSources), handleMappingFields is called with childToParentHighPriority = true, so under TwoWay the child’s value takes precedence.

getValuesByEntityDataSources(spaceId, dataEntity, dataEntry, isUpdateMode) returns a Map<toFieldId, value> (values may be arrays for repeatable blocks):

  1. For each dataSources entry, load the referenceEntity (cached in a local map) and locate the referenceField by id.
  2. Read the reference value at referenceField.fullNormalizedName. If empty and the field’s options.autoSelectFirstValue is set, fall back to DataEntryService.getDefaultFirstValue. If still empty and the field is calculated or has an on-form-opened trigger, run calculateField.
  3. If the reference field sits inside a repeatable block (isParentBlockRepeatable + blockNormalizedName), iterate each block instance; a block with no dataEntry reference pushes null for every mapped target. Otherwise resolve the single referenced entry.
  4. For each mapped field, handleMappingFields loads the source entry (state = Active, isInvalid = false) and applies the update-mode rules above. Repeatable target blocks are matched by the block whose reference field’s dataEntry === sourceEntryId.

Only fields whose mapping.enabled is true are populated; disabled targets are skipped.

Separately from the create/update pass above, an event handler pushes changes made on a parent entry to entries that map from it, for mapped fields in ParentOnly or TwoWay mode; for a TwoWay mapped field, a change made on the child is also written back to the parent entry (UpdateMapFieldValueEntryCreatedHandler / UpdateMapFieldValueEntryUpdatedHandler in data-service). Local and Never targets are never refreshed from a later parent change.

LinksService builds the authenticated sidebar tree — a different kind of “reference”: a link node that points at a resource. Links are entries of the link entity (LINK_ENTITY_NORMALIZED_NAME).

LinkType values: Module = '0', View = '1', Page = '2', Report = '3', Untyped = '4'.

Reports are web-only. A report link opens only in the web app; on mobile it resolves to a NotSupportedLink and cannot be navigated to.

Sidebar entries are managed through the Links entity, whose entries can be either manually owned or system-owned. System-owned links are maintained automatically: when a module, view, or report is created, updated, or deleted, the system creates, updates, or removes the corresponding Links entry. Manually added entries let an administrator place custom nodes in the sidebar, choosing type (Module, View, Page, Report, Untyped), icon, name, description, parent (for hierarchy), publish state, and permissions (Authenticated, Anonymous, Restricted, Everyone). Entries are ordered by the Order field, smallest to largest. Each manual entry also has a Target section whose sub-fields depend on the type: Link (the URL, used when the type is Uncategorized), Target ID (auto-filled for system-owned entries), and Target View Action (the view link, used when the type is View). Entries with system ownership inherit all their settings from their source — a View entry, for example, adopts its settings from the view configuration.

getLinksForSidebar(domain, spaceId, userId, delegationId?) assembles the tree:

  • Anonymous (no userId): includes links whose authentication.type.id is 0 (Anonymous) or 2 (Everyone), plus 1 (Authenticated) links whose value.type.id is '0'.
  • Authenticated: includes types 1 and 2, plus 3 (Restricted) links where the user (or one of their groups) appears in value.authentication.users / groups.
  • All links must be published: true, state: 1, match the domain (empty domain = all), and satisfy sharing (ApplicationSharingLevelEnum Public, or Private/Shared scoped to spaceId). Ordered by value.order ASC, then value.title.en ASC.
  • When a delegationId is present, filterLinksByDelegatedPermissions drops view/report/page links whose target id is not among the delegatee’s allowed resources.
  • The tree is assembled by parent id; a Module node with no children is pruned. View links whose parent is hidden are skipped.

Related helpers: createLinkForModule builds a system-owned module LinkDataEntryValue; archiveExistingLinks(targetId, userId, correlationId) sends an ArchiveDataEntriesCommand for all active links pointing at a target (used to clean up when the underlying resource goes away).

Besides sidebar links, OSOS provides system links — shareable, token-based links that resolve to a specific target: a data view, a page/generic view, a report, or a module. They carry:

  • Token — a unique token bound to the target; the system mints a signed link and resolves the token when the link is opened, directing the visitor to the intended target.
  • Target — the view, page, report, or module the link resolves to.
  • Authentication type — anonymous (public access without signing in) or authenticated (requires login).
  • Validity / expiry — a validity period and expiry date; a link can be enabled, disabled, have its validity updated, or be removed.

Anonymous links expose public views to unauthenticated visitors; to protect these views the system adds a human-verification (CAPTCHA) step, and the target can be inspected before sharing via Preview Mode.

  • targetField side depends on direction. Incoming: targetField lives on targetEntity. Outgoing: it lives on the owning dataEntity. Get this wrong and transformToRelationDto will fail to resolve the field.
  • Outgoing relations are ephemeral. They have composite ids and no document — you cannot PATCH/DELETE them; those routes operate on stored documents via findById.
  • Implicit relations are immutable through the API.
  • updateIdentifier is mandatory for safe updates. Omitting it skips the conflict check (the guard only fires when a differing value is supplied), so clients should round-trip the token.
  • findAll caps results at 500 and defaults to 100 — paginate for large tenants.
  • Mapping only writes mapping.enabled targets, and Never/Local deliberately protect local edits; a value “not updating” is often the intended update-mode behavior, not a bug.
  • Adding a mapped or application-reference field required saving twice. The entity designer’s field list renders each item bound to a plain form control, but the mapped-field and application-reference-field dialogs used to insert a differently-shaped (nested) control — the new field appeared in the list, but a save did not pick up its value until something else re-wired it. Fixed by inserting the same plain-control shape the rest of the field list uses.

Platform 1.10.0 · Backend 1.11.0-alpha.11 · Frontend 1.11.0-alpha.6 · Mobile 1.10.2 · Chart 1.11.8 · Gateway 2.6.11 · MCP 0.2.0 · Grafana DS 1.2.0Docs build 2026-11-27