How to set foreign key with a smart collection

Context

I have a smart collection “Contact” (contacts are section of table Users that have status=client).
Other table “Besoins” that has a foreign key user_id that refers to the collection Users.

Here is a screenshot of collection Besoins:


When I click on the contact link it goes to Collection Users, however I want that this link goes to smart collection Contact.

This is the relationship in the Besoin Model:

I dont have a Model Contact since it’s a smart collection, I got only forest/contact.js and routes/contact.js.

Feature(s) impacted

Link between two collections

Observed behavior

link goes to collection “Users” instead of smart collection “Contact”

Expected behavior

Link should be to the smart collection “Contact”

  • Project name: Clevermate
  • Environment name: Test
  • Database type: POSTGRES

Hello @Adel_de_Clevermate,

I think it should be possible by creating a new smart field referencing your contact collection.

We cannot change the model and the relationship between Besoins and Users as it is defined like this in your model.

But it’s possible to create a new “smart” field that will add this “fake” relationship.

You can find some documentation about smart relationships in the documentation. Let me know if it solves your issue.

1 Like

Hi @GuillaumeGautreau

This helps so far, thank you!

Following the Doc, I implemented a new smart field (contact_ref) to add a relationship, it gets the contact as you see here


But it is not shown as a Link as expected.

this the the smart field:

Do you have any idea why this happens, please?

Hello @Adel_de_Clevermate,

I reproduced your use case locally with a different DB, and I could manage to have a link between the 2.

I experienced an issue when the field name contained the character _. Could you rename your field contactRef and see if it works?

If it fixes your issue, I also suggest replacing the getter by:

collection("cBesoins", {
  fields: [{
    field: 'contactRef',
    type: 'String',
    reference: 'contacts.id',
    get: (besoin) => besoin.user
  }]
});

As there is a relationship between besoin and user, the linked user should have already been loaded.

For your information, we released a new agent package named @forestadmin/agent, along with @forestadmin/datasource-sequelize that has a more robust and simpler coding interface.

We strongly advise people switching to this new agent because it will replace the forest-express based solution in the long term.

Thanks @GuillaumeGautreau !
It worked for me when I replaces contact_ref by contactRef.

1 Like