How to query models where relationship is null in Strapi?

Viewed 1758

I have a model Category with a belongs to many relationship with itself:

  • Category has many categories in subcategories
  • Category belongs to one category in supercategory

When I query all categories I get the correct results:

  • strapi.services.category.find()

When I query all subcategories I also get the correct results:

  • strapi.services.category.find({ supercategory_null: false })

But when I query just supercategories it doesn't return any categories:

  • strapi.services.category.find({ supercategory_null: true })

Question

How can I query just the categories that have no supercategory relationship?

2 Answers

This should work

strapi.services.category.find({ supercategory_null: true },['category']);

Defination: find(params, populate)

populate (array): you have to mention data you want populate e.g ["author", "author.name", "comment", "comment.content"]

The solution I found is to use knex instead of the strapi api:

// Assuming your table name is `category`
const knex = strapi.connections.default;
const categories = await knex(`category`).select(`*`).where(`supercategory`, null);
Related