Show TOC

Foreign KeysLocate this document in the navigation structure

Syntax Form
foreign_key_annotations
...
  WITH FOREIGN KEY [[1,m]] check_table
    WHERE check_field1 = structure.component1
      [AND check_field2 = structure.component2 ...];
...
Definition

You can add a foreign key relationship to an elementary component. For this, you add the WITH FOREIGN KEY keywords, followed by the name of the check table and the assignments, to its check fields as a WHERE condition. Single assignments are connected with the AND keyword.

Notes

If you define a foreign key for a component or on a component extension, you should add foreign key annotations.

You can define an optional [n:m] cardinality for each foreign key. In structures, cardinalities serve for docmentattion purposes only. In the source code editor,

  • n relates to records typed with the surrounding structure
  • m relates to entries in the check table

Possible Values for n

  • [1]: Precisely one record must exist for each row in the check table.
  • [0..1]: There can be no more than one record for each row in the check table.
  • [1..*]: There must be at least one record for each row in the check table.
  • [0..*]: There can be any number of records for each row in the check table.

Possible Values for m

  • [1]: Precisely one row in the check table must exist for each record.
  • [0..1]: No assigned rows must exist in the check table for a record.

Example

The elementary component department_id has a foreign key relationship with the sdepartment check table. In this relationship, the mandt component for entries in the check table must match the sy-mandt field and the id component of the check table must match the department_id field of any record based on this structure.

The cardinality defines that for each record an entry should exist in the check table, but not vice versa.

If the foreign key check fails, the message with the number 001 of the employee_messages message class is displayed.

...
  @AbapCatalog.foreignKey.label : 'Departments'
  @AbapCatalog.foreignKey.keyType : #KEY
  @AbapCatalog.foreignKey.screenCheck : true
  @AbapCatalog.foreignKey.messageClass : 'employee_messages’
  @AbapCatalog.foreignKey.messageNumber : '001'
  department_id : dtel_department WITH FOREIGN KEY [0..*,1] sdepartment 
    WHERE mandt = syst.mandt 
      AND id = employee.department_id;
...