Skip to main content
Smart relationships work very differently between v1 and v2. In legacy agents, smart relationships were declared as smart fields with a reference property:
  • Many-to-one / one-to-one: implemented via the get function returning a single record
  • One-to-many / many-to-many: implemented by creating all CRUD routes on a router file
The new system is completely different: it is based on primary keys and foreign keys.

When the foreign key is accessible

If the foreign key already exists in your data:
// Many-to-one
collection('order', {
  fields: [{
    field: 'delivery_address',
    type: 'String',
    reference: 'Address._id',
    get: async order => models.addresses.find({ id: order.delivery_address_id }),
  }],
});

// Reverse relationship
collection('address', {
  fields: [{ field: 'orders', type: ['String'], reference: 'Order.id' }],
});

router.get('/address/:id/relationships/orders', (req, res) => { /* ... */ });

When you need complex logic to get the foreign key

If the foreign key doesn’t exist in your database and requires custom logic:
  1. Create a computed field that contains the foreign key value
  2. Make that field filterable with the In operator (required for relationships to work)
  3. Declare the relationship using the computed field as the foreign key
If the foreign key exists in a related table but not the current one, use import field instead. It’s faster and natively filterable.
collection('order', {
  fields: [{
    field: 'delivery_address',
    type: 'String',
    reference: 'Address._id',
    get: async order => models.addresses.find(/* complex query */),
  }],
});