This text will show you how you can bind two entities using a foreign key (FK).
A foreign key is used to link two relational database tables. It is a field or a group of fields in one table that uniquely identifies a row of another table (primary key).
[!success]- Prerequisites for further work
In order to create a foreign key, there are 2 basic prerequisites you need to meet:
In the ORIGAM Architect, there are two ways of how to create a foreign key – using an action (wizard) and manually.
Foreign key with Action
When using Action, the wizard will create a new field for you and then make it a foreign key. To do that, just right-click in the Model browser on the entity for which you want to create the field with FK and choose Action / Create Foreign Key…:
A wizard will popup:
The second screen of the wizard may be filled in the following way:
In case the target field already has a Lookup created, you can select it here. Also, if the field should be obligatory, then deselect the option Allow Nulls.
This is what the wizard will create for you:
And here is your FK field created after you click on the Start button:
When you click on the Show result button, the wizard will get you into the Find results tab in the Model browser:
When you double-click on the new field created, you will jump to the Model browser tab and see your new FK field also there:
Now double-click the field to see the details of it, and all the fields that the wizard filled in for you:
Manual procedure
In order to be able to create a Foreign key field manually, you have to create the field for it first. The convention of ORIGAM is that to the basic FK field name, we add _Id
suffix. So, for example, if we have an entity named Task
and a field named Priority
in it in which we want to store the Id of the priority stored in the table Priorities
, we name that field Priority_Id
.
This naming convention helps to recognize at the first look that such a field contains a foreign key and is linked to a certain record, a primary key, of another entity.
The DataType of a field that holds a foreign key needs to be set as UniqueIdentifier
:
More on database field creation, you can find here.
Once you have the FK field created, then choose in the field settings the ForeignKeyEntity and target ForeignKeyField, which will be usually Id
– as the default unique identifier of any record:
Once you save that, your FK is created.
Foreign key in the database
Now let’s have a look at how the creation of an FK field is reflected in the database.
To reflect your changes, you need to run the deployment script first. In case you are not familiar with that, have a look here.
Once you mirror the changes made in the application model in the ORIGAM Architect, you can check the changes in your database as well:
More on working with the database, you can find in this article.