strapi icon indicating copy to clipboard operation
strapi copied to clipboard

Filter on relation

Open johannpinson opened this issue 8 years ago β€’ 29 comments

What is the expected behavior?

I look into the doc and github, but can’t find how to solve this problem:

How can I add a filter (where) to a relation?

URL: http://localhost:1337/platform Response:

[
    {
        "isPublished": true,
        "_id": "5b0bd96f6ec604b0254367ef",
        "type": "STANDARD",
        "name": "main",
        "createdAt": "2018-05-28T10:26:55.999Z",
        "updatedAt": "2018-05-28T10:26:56.044Z",
        "__v": 0,
        "id": "5b0bd96f6ec604b0254367ef",
        "platformModels": [
            {
                "type": "STANDARD",
                "_id": "5b0bd95f6ec604b0254367ed",
                "name": "a",
                "createdAt": "2018-05-28T10:26:39.359Z",
                "updatedAt": "2018-05-28T10:26:56.048Z",
                "__v": 0,
                "id": "5b0bd95f6ec604b0254367ed",
                "platform": "5b0bd96f6ec604b0254367ef"
            },
            {
                "type": "SLIM",
                "_id": "5b0bd9646ec604b0254367ee",
                "name": "b",
                "createdAt": "2018-05-28T10:26:44.235Z",
                "updatedAt": "2018-05-28T16:01:06.381Z",
                "__v": 0,
                "id": "5b0bd9646ec604b0254367ee",
                "platform": "5b0bd96f6ec604b0254367ef"
            }
        ]
    }
]

For example, can we have a URL like : http://localhost:1337/platform?platformModels={"type_ne":"STANDARD"}

It will allow to filter inside relations from specific rules/fields

johannpinson avatar May 29 '18 08:05 johannpinson

This is a must have feature, I also need this

mig4ng avatar Jun 02 '18 23:06 mig4ng

Hi @johannpinson ! Actually this feature is not developed.

lauriejim avatar Jun 05 '18 18:06 lauriejim

Hey @lauriejim Yes we talk about in Slack.

Actually, we can target a many-to-one, like http://localhost:1337/platformmodels?platform=ID to filter into relation, because the platform fields is an object and not an array in this side of the relation.

This is my actually code to make the filter working:

Platform
  .find()
  .where(convertedParams.where)
  .sort(convertedParams.sort)
  .skip(convertedParams.start)
  .limit(convertedParams.limit)
  // .populate(_.keys(_.groupBy(_.reject(strapi.models.platform.associations, {autoPopulate: false}), 'alias')).join(' '));
  .populate([
    {
      path: 'platformModels',
      match: { type: 'STANDARD' }, // make dynamic with convertedParams.relation?!
      options: { limit: 5 },
    },
    {
      path: 'posts',
      options: { limit: 10 },
    },
  ]);

My next step will be to make it dynamic the populate with some like:

.populate(strapi.models.platform.associations.filter(item => item.autoPopulate).map(item => item.alias).join(' '))

johannpinson avatar Jun 07 '18 08:06 johannpinson

@lauriejim

This is a proposition about filter on a relation x-to-many:

  • The relation entity will need to have _relation at the end
  • Then the field inside the relation is attach like an object, aka .field
  • This gives something like platformModels_relation.type in my case

Of course, I already test the system to handle some case like platformModel_relation.type_ne πŸ˜‰

Are you ok with this specs?

johannpinson avatar Jun 07 '18 10:06 johannpinson

I found it interesting but I have to think more about this point.

Need also @Aurelsicoko feedback.

lauriejim avatar Jun 07 '18 16:06 lauriejim

@johannpinson Why do you need to add the _relation suffix whereas we know that a field is relational or not?

Aurelsicoko avatar Jun 08 '18 16:06 Aurelsicoko

It was just a proposal to simplify my actual code and avoid to search if the param matches to an existing attribute πŸ˜„

But in all case, we will need to separate this kind of filter of where:

cf. strapi-utils/lib/models.js

const convertParams = {
  where: {},
  sort: '',
  start: 0,
  limit: 100,
  relation: {},
};
} else if (key.match('_relation.')) {
  const [keyModel, keyAttribute] = key.split('.');
  const model = keyModel.replace('_relation', '')

  let type = '=';
  if (keyAttribute.match(/_{1}ne|lte?|gte?|containss?/)) {
    type = keyAttribute.match(/_{1}ne|lte?|gte?|containss?/)[0]
  }
  key = keyAttribute.replace(type, '')

  result = convertor(value, type, `relation.${model}.${key}`)
  result.key = result.key.replace('where.', '')
} else {

and inside the service:

.populate(
  strapi.models.platform.associations.filter(item => item.autoPopulate).map(
    item => ({
      path: item.alias,
      match: convertedParams.relation[item.alias],
      options: { limit: 10 },
    })
  )
);

But yes, in fact we can also detect the "type" of relation:

Object.keys(attributes).forEach(
  (item) => {
    // is still undefined is not a relation?
    console.log(this.getNature(attributes[item], item, models, model))
  }
)

johannpinson avatar Jun 08 '18 17:06 johannpinson

So, it means that we shouldn't see differences in the URL but only in the services. It looks good to me πŸ‘

Example: http://localhost:1337/post?title_contains=john&authors={type: "administrator"}

Aurelsicoko avatar Jun 11 '18 12:06 Aurelsicoko

Hey @Aurelsicoko I thought about this type of url: http://localhost:1337/post?authors_relation.type=administrator

It will avoid to encode special characters like {, " or space.

Moreover it can be combined like: http://localhost:1337/post?authors_relation.type_ne=administrator

johannpinson avatar Jun 19 '18 11:06 johannpinson

@johannpinson Why we can't do this http://localhost:1337/post?authors.type_ne=administrator? As I said, we know that the author is a relation, we don't need to specify it in the URL.

Aurelsicoko avatar Jun 22 '18 14:06 Aurelsicoko

Yes I think we can detect if a variable is a relation, but it was just to simplify the logic and avoid a new iteration to check each parameter to know if it's an attribute or a relation πŸ˜„ => So, what it the best solution for you? It need to iterate the strapi.models.attribute-like list or there is a function like getNature() to detect it easily?

Moreover, a oneToX relation doesn't need to catch the same logic, because if we have a author field (only one person car write a post), we can have xxx/post?author=123 to filter by author and not xxx/post?author.id=123

johannpinson avatar Jun 22 '18 15:06 johannpinson

I personally prefer xxx/post?author.id=123 and I think it doesn't cost anything to check in the backend if an attribute is relational or not. We're talking about a loop with less than 20 items πŸ™ˆ

Aurelsicoko avatar Jun 26 '18 10:06 Aurelsicoko

@Aurelsicoko can probably close this issue in favor of: https://portal.productboard.com/strapi/c/38-filters-on-relational-attributes

derrickmehaffy avatar Nov 09 '18 21:11 derrickmehaffy

Sorry , so how do I filter on relations its not clear in this thread how this has been completed.

qorrect avatar Nov 24 '18 20:11 qorrect

@qorrect you can't yet until the PR is merged. This issue was closed as the feature was moved to the project board.

derrickmehaffy avatar Nov 24 '18 23:11 derrickmehaffy

No updates on this? I really need this feature...

delucca avatar Dec 20 '18 19:12 delucca

@odelucca we tried to implement this feature by merging this PR https://github.com/strapi/strapi/pull/1948 made by @kamalbennani. However, it was a fail and it caused a lot of issues, so we reverted the changes. We'll try to re-implement it soon.

Aurelsicoko avatar Dec 21 '18 15:12 Aurelsicoko

@lauriejim I've a similar issue, ever simpler. If we follow the Platform Model above, I would have a query with an url like:

http://localhost:1337/platform?platformModels=x|y where x e y are two platformModels IDs. That means the possibility of query for: All the platforms that have 2 specific platformModels.

Now, I can only have the simple case: http://localhost:1337/platform?platformModels=x

Is there a way to do that ? Is there a simple way to extend the query to a list of IDs ? Thanks!

Vivsss avatar Jan 04 '19 19:01 Vivsss

You want plateforms that have (x and y) or (x or y) ? In any case it's actually not possible by default. You will have to custom the generated API code to make it work with you needs.

lauriejim avatar Jan 06 '19 13:01 lauriejim

@lauriejim thanks for your reply ! Both cases (AND/OR) are really interesting for me.. Since I'm a beginner with coding customs API, should you have some site reference for this kind jobs, with snippets or examples?

Vivsss avatar Jan 07 '19 18:01 Vivsss