# BelongsToMany edition through smart collection

{% hint style="warning" %}
Please be sure of your agent type and version and pick the right documentation accordingly.
{% endhint %}

{% tabs %}
{% tab title="Node.js" %}
{% hint style="danger" %}
This is the documentation of the `forest-express-sequelize` and `forest-express-mongoose` Node.js agents that will soon reach end-of-support.

`forest-express-sequelize` v9 and `forest-express-mongoose` v9 are replaced by [`@forestadmin/agent`](https://docs.forestadmin.com/developer-guide-agents-nodejs/) v1.

Please check your agent type and version and read on or switch to the right documentation.
{% endhint %}
{% endtab %}

{% tab title="Ruby on Rails" %}
{% hint style="success" %}
This is still the latest Ruby on Rails documentation of the `forest_liana` agent, you’re at the right place, please read on.
{% endhint %}
{% endtab %}

{% tab title="Python" %}
{% hint style="danger" %}
This is the documentation of the `django-forestadmin` Django agent that will soon reach end-of-support.

If you’re using a Django agent, notice that `django-forestadmin` v1 is replaced by [`forestadmin-agent-django`](https://docs.forestadmin.com/developer-guide-agents-python) v1.

If you’re using a Flask agent, go to the [`forestadmin-agent-flask`](https://docs.forestadmin.com/developer-guide-agents-python) v1 documentation.

Please check your agent type and version and read on or switch to the right documentation.
{% endhint %}
{% endtab %}

{% tab title="PHP" %}
{% hint style="danger" %}
This is the documentation of the `forestadmin/laravel-forestadmin` Laravel agent that will soon reach end-of-support.

If you’re using a Laravel agent, notice that `forestadmin/laravel-forestadmin` v1 is replaced by [`forestadmin/laravel-forestadmin`](https://docs.forestadmin.com/developer-guide-agents-php) v3.

If you’re using a Symfony agent, go to the [`forestadmin/symfony-forestadmin`](https://docs.forestadmin.com/developer-guide-agents-php) v1 documentation.

Please check your agent type and version and read on or switch to the right documentation.
{% endhint %}
{% endtab %}
{% endtabs %}

## BelongsToMany edition through smart collection

**Context:** *A customer success team has to onboard “experts”, and those “experts” can have multiple “skills”, modelled via a belongsToMany relationship between “experts” and “skills” tables through an “experts\_skills” table; the skills table has \~200 records and experts usually have between 5 to 30 of them.*

*Unfortunately this is quite painful to edit in forest admin right now since when you want to add a new item in a belongToMany relationship in forest admin you have to:*

* *click on “add an existing …”*
* *Remember and search for the item using a single search bar*
* *select the desired item*

#### Intro

In the following we will see how the choice of `skills` to be added to an expert can be materialized through a searchable smart collection named `otherSkills` displayed as related data of an `expert`. An action applicable on the selected records of this collection will allow to associate new skills to an expert.

{% embed url="<https://www.loom.com/share/86149f74da524e7499bea4bde5b51e17>" %}

**Data models**

The data models we have been working with here (`experts` and `skills`) are the following:

```jsx
// This model was generated by Lumber. However, you remain in control of your models.
// Learn how here: <https://docs.forestadmin.com/documentation/v/v6/reference-guide/models/enrich-your-models>
module.exports = (sequelize, DataTypes) => {
  const { Sequelize } = sequelize;
  // This section contains the fields of your model, mapped to your table's columns.
  // Learn more here: <https://docs.forestadmin.com/documentation/v/v6/reference-guide/models/enrich-your-models#declaring-a-new-field-in-a-model>
  const Experts = sequelize.define(
    'experts',
    {
      username: {
        type: DataTypes.STRING,
      },
    },
    {
      tableName: 'experts',
      timestamps: false,
      schema: process.env.DATABASE_SCHEMA,
    }
  );

  // This section contains the relationships for this model. See: <https://docs.forestadmin.com/documentation/v/v6/reference-guide/relationships#adding-relationships>.
  Experts.associate = (models) => {
    Experts.belongsToMany(models.skills, {
      through: 'experts_skills',
      foreignKey: 'expert_id',
      otherKey: 'skill_id',
      as: 'expertSkills',
    });
  };

  return Experts;
};
```

```jsx
// This model was generated by Lumber. However, you remain in control of your models.
// Learn how here: <https://docs.forestadmin.com/documentation/v/v6/reference-guide/models/enrich-your-models>
module.exports = (sequelize, DataTypes) => {
  const { Sequelize } = sequelize;
  // This section contains the fields of your model, mapped to your table's columns.
  // Learn more here: <https://docs.forestadmin.com/documentation/v/v6/reference-guide/models/enrich-your-models#declaring-a-new-field-in-a-model>
  const Skills = sequelize.define(
    'skills',
    {
      description: {
        type: DataTypes.STRING,
      },
    },
    {
      tableName: 'skills',
      timestamps: false,
      schema: process.env.DATABASE_SCHEMA,
    }
  );

  // This section contains the relationships for this model. See: <https://docs.forestadmin.com/documentation/v/v6/reference-guide/relationships#adding-relationships>.
  Skills.associate = (models) => {
    Skills.belongsToMany(models.experts, {
      through: 'experts_skills',
      foreignKey: 'skill_id',
      otherKey: 'expert_id',
      as: 'skillExperts',
    });
  };

  return Skills;
};
```

#### Step 1: create a smart collection 'other skills'

As we already have the skills assigned to an expert as related data when viewing an expert, we'd like to see the skills that have not been assigned and could be by the user.

For this we need to create a smart collection called `otherSkills`. This smart collection is defined in a file `other-skills.js` inside the `forest` folder.

```jsx
const { collection } = require('forest-express-sequelize');

collection('otherSkills', {
  fields: [
    {
      field: 'description',
      type: 'String',
    },
  ],
});
```

#### Step 2: declare a smart relationship between experts and otherSkills

In order to display records from the collection `otherSkills` as related data of an expert, we need to declare a smart relationship between these collections. This is done in the file `experts.js` of the `forest` folder.

```jsx
const { collection } = require('forest-express-sequelize');

collection('experts', {
  actions: [],
  fields: [
    {
      field: 'otherSkills',
      type: ['String'],
      reference: 'otherSkills.id',
    },
  ],
  segments: [],
});
```

#### Step 3: implement the logic to retrieve records from the smart relationship

We want to display as related data the `skills` that are not already assigned to an `expert` so we can add them. Therefore when implementing the route called to retrieve records from the collection `otherSkills` through the smart relationship, we need to add this logic. This is done in the file `experts.js` of the `routes` folder.

\<aside> 💡 We've added the logic needed to perform searches in the snippet below.

\</aside>

```jsx
const express = require('express');
const {
  PermissionMiddlewareCreator,
  RecordSerializer,
} = require('forest-express-sequelize');
const { Op } = require('sequelize');
const { otherSkills, experts, skills } = require('../models');

const router = express.Router();
const permissionMiddlewareCreator = new PermissionMiddlewareCreator('experts');
const recordSerializer = new RecordSerializer({ name: 'otherSkills' });

router.get(
  '/experts/:id/relationships/otherSkills',
  permissionMiddlewareCreator.list(),
  (request, response, next) => {
    const expert = experts.findByPk(request.params.id, {
      include: [
        {
          model: skills,
          as: 'expertSkills',
        },
      ],
    });
    let queryParams = {};
    if (request.query.search) {
      queryParams = {
        where: {
          description: {
            [Op.iLike]: `%${request.query.search}%`,
          },
        },
      };
    }
    const skillsList = skills.findAll(queryParams);
    Promise.all([expert, skillsList])
      .then((results) => {
        const { expertSkills } = results[0];
        const allSkills = results[1];
        const expertSkillsIds = expertSkills.map((record) => record.id);
        const records = [];
        allSkills.forEach((skillListed) => {
          if (
            !expertSkillsIds.includes(skillListed.id) &&
            skillListed.description
          ) {
            const skill = {
              id: skillListed.id,
              description: skillListed.description,
            };
            records.push(skill);
          }
        });
        return records;
      })
      .then((records) => recordSerializer.serialize(records))
      .then((recordsSerialized) =>
        response.send({
          ...recordsSerialized,
          meta: { count: recordsSerialized.data.length },
        })
      );
  }
);

module.exports = router;
```

#### Step 4: create the smart action to add skills to an expert

Next step is to declare a smart action that will allow a user to select several records of the `otherSkills` smart collection and associate them to an `expert`. This action is declared in the file `other-skills.js` of the `forest` folder.

```jsx
const { collection } = require('forest-express-sequelize');

collection('otherSkills', {
  actions: [{
    name: 'add',
    type: 'bulk',
  }],
  ...
});
```

The logic to be triggered when a call is made to the route is implemented as follows in the `other-skills.js` file of the `routes` folder.

```javascript
const express = require('express');
const { PermissionMiddlewareCreator } = require('forest-express-sequelize');
const { experts } = require('../models');

const router = express.Router();
const permissionMiddlewareCreator = new PermissionMiddlewareCreator(
  'otherSkills'
);

router.post(
  '/actions/add',
  permissionMiddlewareCreator.smartAction(),
  (request, response) => {
    const expertId = request.body.data.attributes.parent_collection_id;
    const selectedIds = request.body.data.attributes.ids;
    experts
      .findByPk(expertId)
      .then((user) => {
        selectedIds.forEach((skillId) => {
          user.addExpertSkills(skillId);
        });
      })
      .then(() =>
        response.send({
          success: `${selectedIds.length} new skills have been added`,
        })
      );
  }
);

module.exports = router;
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.forestadmin.com/documentation/reference-guide/actions/smart-action-examples/belongstomany-edition-through-smart-collection.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
