Filtering a HasMany Smart Relationship

Hi,
I have a smart relationship like described here Create a Smart relationship - Documentation

In the UI I can apply filters on this relationship. The problem is, that the filter seems to be ignored in this example because request.query.filters is not applied.
Is it possible to also apply the filter query when searching for the relations?

Hello @bef,

Thanks for reaching out :raised_hands:

To sum up, you created a has-many smart relationship, and you wish to be able to filter it in the UI when being on Related data?

Did you override the relationship route? Could you share it with us?
To make the filter taken into account, you can access it thanks to request.query.filters and use it according to your use case.

Hope this helps.
Thanks!

Yes I did overwrite the relationship route.
I did the same as described in the documentation Option 1: using Sequelize ORM

In the provided example customers.findAll is used to search for the related data. The include parameter contains a where clause.
But request.query.filters is ignored. How can I add the request.query.filters to the include parameter? Is there an option to convert it to such a where clause?

Hi @bef :wave: can you share with us your code or an exemple so that I can propose you a piece of code related to your issue :pray:

Here is the code. Mabye request.query.filters can be added to where somehow.

router.get('/user/:recordId/relationships/activity', (request, response, next) => {
  const targetId = `prefix-${request.params.recordId}`
  const limit = parseInt(request.query.page.size, 10) || 20;
  const offset = (parseInt(request.query.page.number, 10) - 1) * limit;
  const recordsGetter = new RecordsGetter(activity, request.user, request.query);

    let where = { [Op.or]: [{ someField: targetId }, { anotherField: targetId }] };
    const findAll = activity.findAll({
        where,
        offset,
        limit,
    });

    const count = activity.count({ where });

    Promise.all([findAll, count])
        .then(([activitiesFound, activitiesCount]) =>
            recordsGetter.serialize(activitiesFound, { count: activitiesCount }))
        .then((recordsSerialized) => response.send(recordsSerialized))
        .catch(next);
});

Thank you, i think something like below do the trick.

const { parseFilter, Schemas } = require('forest-express-sequelize');

router.get('/user/:recordId/relationships/activity', (request, response, next) => {
...
  let where = { [Op.or]: [{ someField: targetId }, { anotherField: targetId }] };

  if (req.query.filter) {
    const parsedWhere = await parseFilter(JSON.parse(req.query.filters), Schemas.schemas.activity, req.query.timezone);
    where = { [Op.and]: [parsedWhere, where] };
  }

  const findAll = activity.findAll({
        where,
        offset,
        limit,
    });

let me know.

3 Likes

Thank you! That solved it.

1 Like