Computed foreign keys
Displaying a link to the last message sent by a customer
agent.customizeCollection('customers', collection => {
// Create foreign key
collection.addField('lastMessageId', {
columnType: 'Number',
dependencies: ['id'],
getValues: async (customers, context) => {
// We're using Forest Admin's query interface (you can use an ORM or a plain SQL query)
const messages = context.dataSource.getCollection('messages');
const conditionTree = {
field: 'customer_id',
operator: 'In',
value: customers.map(r => r.id),
};
const rows = await messages.aggregate(
{ conditionTree },
{ operation: 'Max', field: 'id', groups: [{ field: 'customer_id' }] },
);
return customers.map(record => {
return rows.find(row => row.group.customer_id === record.id)?.value ?? null;
});
},
});
// Implement the 'In' operator.
collection.replaceFieldOperator('lastMessageId', 'In', async (lastMessageIds, context) => {
const records = await context.dataSource
.getCollection('messages')
.list({ conditionTree: { field: 'id', operator: 'In', value: lastMessageIds } }, [
'customer_id',
]);
return { field: 'id', operator: 'In', value: records.map(r => r.customer_id) };
});
// Create relationships using the foreign key we just added.
collection.addManyToOneRelation('lastMessage', 'messages', {
foreignKey: 'lastMessageId',
});
});Connecting collections without having a shared identifier
Last updated