# Relationships

> Name the links between concepts with relationships, declare which models hold them, and follow them in queries

Source: https://taxilang.org/docs/language/relationships

A relationship names a link from one concept to another, like "a person works for a legal entity".

```taxi
type FirstName inherits String
type LastName inherits String
type LegalEntityId inherits String
type LegalEntityName inherits String

concept Person      { FirstName, LastName }
concept LegalEntity { LegalEntityId, LegalEntityName }

[[ The legal entity a person is employed by. ]]
relationship worksFor: Person -> LegalEntity?
```

Models then declare that they hold the relationship, and in queries you follow it by name: `worksFor::LegalEntityName`.

For how relationships fit with concepts and intents, see the [overview](https://taxilang.org/docs/language/ontology).

## Declaring a relationship

A relationship has a name, a source concept, and a target concept, written `source -> target`.
It reads left to right: a `Person` `worksFor` a `LegalEntity`.

The target says how many there are (its cardinality), using `?` and `[]` as for [concept members](https://taxilang.org/docs/language/concepts#how-many-of-each-member):

```taxi
type FirstName inherits String
type LegalEntityName inherits String

concept Person      { FirstName }
concept LegalEntity { LegalEntityName }

// A person works for zero or one legal entity
relationship worksFor: Person -> LegalEntity?

// A person is employed by exactly one legal entity
relationship employedBy: Person -> LegalEntity

// A legal entity employs one or more people
relationship employs: LegalEntity -> Person[]
```

- The source must be a single concept, without `?` or `[]` (`RELATIONSHIP_INVALID_SOURCE`).
- The target must be a concept (`RELATIONSHIP_INVALID_TARGET`).
- A relationship isn't a type or a function. You can't use it as a field type, and you can't call it.

Each relationship stands alone. `employs` isn't automatically the reverse of `worksFor`.

## Models that hold a relationship

A model holds a relationship by listing it in `satisfies`. Each piece of data from that model links one source to its target.

The model can hold the target in two ways: nested in a field, or flat alongside the source.

### Nested

The target is a field, whose type is a model that satisfies the target concept:

```taxi
type FirstName inherits String
type LastName inherits String
type LegalEntityId inherits String
type LegalEntityName inherits String

concept Person      { FirstName, LastName }
concept LegalEntity { LegalEntityId, LegalEntityName }

relationship worksFor: Person -> LegalEntity?

model Employer satisfies LegalEntity {
   lei: LegalEntityId
   legalName: LegalEntityName
}

model Employee satisfies Person, worksFor {
   first: FirstName
   last: LastName
   employer: Employer?
}
```

`Employee` is a `Person`, and its `employer` field holds the `LegalEntity` it works for.
The field can be inside a nested object too, like `job: { employer: Employer }`.

### Flat

The source and the target are both at the same level, like a CSV row or the result of a join:

```taxi
type FirstName inherits String
type LastName inherits String
type LegalEntityId inherits String
type LegalEntityName inherits String

concept Person      { FirstName, LastName }
concept LegalEntity { LegalEntityId, LegalEntityName }

relationship worksFor: Person -> LegalEntity?

model EmploymentRecord satisfies worksFor {
   first: FirstName
   last: LastName
   legalName: LegalEntityName
   lei: LegalEntityId
}
```

`EmploymentRecord`'s own fields satisfy both `Person` and `LegalEntity`.

A flat model can't hold a collection target, like `Person -> LegalEntity[]`. Use a nested collection field instead.

### What the compiler checks

**The model must satisfy the source.** Listing `satisfies worksFor` means the model satisfies `Person` too. You don't need to list `Person` as well, but you can.
If the model doesn't have what `Person` needs, the compiler reports `RELATIONSHIP_SOURCE_NOT_SATISFIED`.

**The model must hold the target.** It needs either a field whose model satisfies `LegalEntity`, or its own fields must satisfy `LegalEntity`. Otherwise the compiler reports `RELATIONSHIP_TARGET_NOT_SATISFIED`.

The target doesn't count as a concept the model satisfies. `EmploymentRecord` satisfies `Person`, but not `LegalEntity`.

**The field's cardinality must fit the relationship's.** For a nested target:

| Relationship target | Field can be |
|---|---|
| `LegalEntity` | `Employer` |
| `LegalEntity?` | `Employer` or `Employer?` |
| `LegalEntity[]` | `Employer[]` |

Anything else is an error (`RELATIONSHIP_TARGET_CARDINALITY_MISMATCH`).

A model can hold several relationships: `model Customer satisfies worksFor, banksWith`.

> **Note: Relationships must be declared**
>
> A model only holds a relationship if it lists it in `satisfies`. A model that has a person and an employer in it, but doesn't declare `worksFor`, doesn't hold `worksFor`. Matching models to relationships by their structure alone isn't supported yet.

## Choosing the target field

If a model has more than one place the target could come from, the compiler can't choose. It reports `RELATIONSHIP_TARGET_AMBIGUOUS`. This happens when:

- two fields could hold the target, or
- a field could hold it, and the model's own fields could also satisfy the target concept.

Pick the right field by adding `satisfies` and the relationship name to it:

```taxi
type PersonId inherits String
type FirstName inherits String
type LastName inherits String
type LegalEntityId inherits String
type LegalEntityName inherits String

concept Person      { PersonId, FirstName, LastName }
concept LegalEntity { LegalEntityId, LegalEntityName }

relationship worksFor:  Person -> LegalEntity?
relationship banksWith: Person -> LegalEntity[]

model Employer satisfies LegalEntity { id: LegalEntityId, name: LegalEntityName }
model Bank     satisfies LegalEntity { id: LegalEntityId, name: LegalEntityName }

model KycProfile satisfies Person, worksFor, banksWith {
   id:       PersonId
   first:    FirstName
   last:     LastName
   employer: Employer? satisfies worksFor
   banks:    Bank[]    satisfies banksWith
}
```

Both `Employer` and `Bank` satisfy `LegalEntity`. The bindings say that `employer` holds `worksFor`, and `banks` holds `banksWith`.

The rules for these bindings:

- The model must list the relationship in its `satisfies` (`RELATIONSHIP_BINDING_WITHOUT_SATISFIES`).
- The field's type must be a model that satisfies the target concept, with a cardinality that fits (`RELATIONSHIP_BINDING_TARGET_MISMATCH`).
- Only one field can bind each relationship (`RELATIONSHIP_BINDING_DUPLICATE`).
- One field can bind several relationships: `employer: Employer satisfies worksFor, employedBy`.

> **Warning: Key fields can't hold a relationship yet**
>
> A relationship has to be held by the target data itself, either nested or flat. A field that only holds the target's id, like `employerId: LegalEntityId satisfies worksFor`, isn't supported yet. The compiler reports `RELATIONSHIP_BINDING_TARGET_MISMATCH`.

## Narrowing a relationship in a child concept

A shared relationship is often too general for a specific part of your domain. A child concept can narrow it.

```taxi
type Isin inherits String
type SecurityName inherits String
type CouponRate inherits Decimal
type MaturityDate inherits Date
type CreditRating inherits String
type LegalEntityId inherits String
type LegalEntityName inherits String

// Shared, general definitions
concept Security { Isin, SecurityName }
concept Issuer   { LegalEntityId, LegalEntityName }
relationship hasIssuer: Security -> Issuer?

// More specific definitions, built on the shared ones
concept BondIssuer inherits Issuer { CreditRating }

concept Bond inherits Security {
   CouponRate,
   MaturityDate,
   hasIssuer -> BondIssuer
}
```

`hasIssuer -> BondIssuer` inside `Bond` says: for a bond, the issuer is exactly one `BondIssuer`, not zero or one plain `Issuer`.
The shared definitions don't change.

A narrowing can:

- change the target to a child concept of the current target
- make the cardinality stricter: `[]` to `?` to exactly one

The compiler reports:

- `CONCEPT_RESTRICTION_NOT_APPLICABLE` if the relationship's source isn't this concept or one of its parents
- `CONCEPT_RESTRICTION_WIDENS_TARGET` if the new target isn't the current target or a child of it
- `CONCEPT_RESTRICTION_WIDENS_CARDINALITY` if the cardinality gets less strict
- `CONCEPT_RESTRICTION_CONFLICT` if two parent concepts narrow the same relationship differently. Fix it by restating the narrowing in the child.
- `CONCEPT_RELATIONSHIP_MEMBER_NEEDS_TARGET` for a relationship name on its own, like `hasIssuer` with no `->`

### What narrowing affects

A narrowing is checked against models that hold the relationship. A model that satisfies `Bond` and holds `hasIssuer` must hold a `BondIssuer`, exactly once:

```taxi
type Isin inherits String
type SecurityName inherits String
type CouponRate inherits Decimal
type MaturityDate inherits Date
type CreditRating inherits String
type LegalEntityId inherits String
type LegalEntityName inherits String
type Price inherits Decimal

concept Security { Isin, SecurityName }
concept Issuer   { LegalEntityId, LegalEntityName }
relationship hasIssuer: Security -> Issuer?

concept BondIssuer inherits Issuer { CreditRating }
concept Bond inherits Security {
   CouponRate,
   MaturityDate,
   hasIssuer -> BondIssuer
}

model RefDataIssuer satisfies BondIssuer {
   id: LegalEntityId
   name: LegalEntityName
   rating: CreditRating
}

// Holds hasIssuer. Its issuer must be exactly one BondIssuer.
model RefDataBond satisfies Bond, hasIssuer {
   isin: Isin
   name: SecurityName
   coupon: CouponRate
   maturity: MaturityDate
   issuer: RefDataIssuer
}

// A Bond with no issuer. This is fine.
model PricedBond satisfies Bond {
   isin: Isin
   name: SecurityName
   coupon: CouponRate
   maturity: MaturityDate
   price: Price
}
```

If `RefDataBond`'s `issuer` were `RefDataIssuer?`, the compiler would report `RELATIONSHIP_TARGET_NOT_SATISFIED`, and say that the requirement comes from `Bond`.

A narrowing doesn't make models hold the relationship. `PricedBond` satisfies `Bond` without any issuer data.
Narrowings aren't members of the concept, so they take no part in checking whether a model satisfies it.

## Following a relationship in a query

In a projection, follow a relationship by name, then pick a value from the target with `::`:

```taxi
type PersonId inherits String
type FirstName inherits String
type LastName inherits String
type LegalEntityId inherits String
type LegalEntityName inherits String

concept Person      { PersonId, FirstName, LastName }
concept LegalEntity { LegalEntityId, LegalEntityName }

relationship worksFor: Person -> LegalEntity?
relationship employs: LegalEntity -> Person[]

model HrEmployer satisfies LegalEntity { id: LegalEntityId, name: LegalEntityName }
model HrEmployee satisfies Person, worksFor {
   id:       PersonId
   first:    FirstName
   last:     LastName
   employer: HrEmployer?
}

service HrApi {
   operation employee(PersonId): HrEmployee
}
```

```taxi
given { PersonId = 'p-1' }
find { HrEmployee } as {
   name:     FirstName
   employer: LegalEntityName? = worksFor::LegalEntityName
}
```

`worksFor::LegalEntityName` means "the `LegalEntityName` of the legal entity this person works for".
The query doesn't need to know that it's held in the `employer` field. The compiler works that out from the model's declaration.

You can follow a relationship from:

- a model that satisfies its source concept, like `HrEmployee`
- the source concept itself, like `find { Person }`
- a child of the source concept

If the thing you're projecting isn't one of these, the relationship isn't in scope, and the compiler reports it as an unknown name.

When the model you're projecting doesn't hold the relationship itself, the query engine looks for another source of data that does. For example, an operation that returns a model holding `worksFor`, and can be called with the values you already have.

### Types and cardinality

The value's type comes from the relationship's target:

- `worksFor` is `LegalEntity?`, so `worksFor::LegalEntityName` may be empty. The field must be optional: `LegalEntityName?`. A required field is an error (`TRAVERSAL_CARDINALITY_MISMATCH`).
- After a `[]` relationship, every step must use `[]`:

```taxi
find { LegalEntity } as {
   name:  LegalEntityName
   staff: FirstName[] = employs::FirstName[]
}
```

Writing `employs::FirstName` without `[]` is an error (`TRAVERSAL_SCALAR_AFTER_COLLECTION`).

### Narrowing in queries

Narrowings on concepts apply in queries too. The compiler uses the type you wrote in `find`.
Using the securities schema from [What narrowing affects](#what-narrowing-affects):

```taxi
given { Isin = 'XS123' }
find { PricedBond } as {
   price:  Price
   issuer: LegalEntityName = hasIssuer::LegalEntityName
   rating: CreditRating    = hasIssuer::CreditRating
}
```

`PricedBond` satisfies `Bond`, and `Bond` narrows `hasIssuer` to exactly one `BondIssuer`. So:

- `hasIssuer::LegalEntityName` is exactly one value, and `issuer` can be a required field.
- `hasIssuer::CreditRating` is available, because a `BondIssuer` has a `CreditRating`.

From `find { Security }`, the same `hasIssuer::LegalEntityName` would be optional, and `hasIssuer::CreditRating` would be an error (`CONCEPT_MEMBER_NOT_FOUND`), because a plain `Issuer` has no `CreditRating`.

### Where you can follow a relationship

- Only on the right-hand side of a field in a projection. Not as a `find` target, and not in criteria.
- A relationship can't be called. `worksFor()` or `worksFor(this.id)` is an error (`RELATIONSHIP_NOT_CALLABLE`).

> **Warning: Query execution is coming**
>
> Queries that follow relationships compile, and they're type-checked against your schema. Support for running them is still being built in the query engine.

## Next steps

- [Concepts](https://taxilang.org/docs/language/concepts): declaring the concepts at each end of a relationship
- [Projections](https://taxilang.org/docs/taxiql/projections): more on shaping query results
