Relationships when you need complex logic to get a foreign key
In this example, we want to create a relationship between the order collection and the address collection (assuming that it does not already exist in the database because depends on complex logic).
We can see that in the legacy agent, the delivery_address field was a smart field that returned the full address of the order, while in the new agent, we will create a computed field that will contain the address ID (the foreign key), and then create the relationship.
We won't be detailing the migration of a relation to a list of records here, but it is very similar to the one described below.
This will be much faster and will not require In filter operators to be implemented (as unlike computed fields, imported fields are natively filterable and sortable).
agent.customizeCollection('order', orders => {
// Create a computed field that will contain the address ID (the foreign key)
orders.addField('deliveryAddressId', {
columnType: 'Number',
dependencies: ['id'],
getValues: async orders => {
const addressByOrderId = await models.addresses.find(/* complex query */);
return orders.map(order => addressByOrderId[order.id].id);
},
});
// Make the field filterable (this is required for the relationship to work)
orders.replaceFieldOperator('deliveryAddressId', 'In', (value, context) => {
// implement the reverse-lookup logic here
});
// Create the relationship
orders.addManyToOneRelation('deliveryAddress', 'address', {
foreignKey: 'deliveryAddressId',
});
});
If the foreign key was already present in the database in a related table, use the feature to move it to the correct collection instead of using a computed field.