How to set Limit of a relation

  • Node.js version: 16.13.1
  • NPM version: 8.3,2
  • Strapi version: 4.0.3
  • Database:
  • Operating system: Windows 10 64 bit

I have created one collection called article and make a component Related_Article inside that i have given the relation to this article but i want that admin only put 3 Related_article after that the strapi shows an error or some message that you couldn’t add more and i am findining every possible solution but it doesn’t work

Help me if you have anything.

1 Like

I think you want to modify the api::article.article 's create() function logic. and you can add a new customize controller. here is the docs: Backend customization - Controllers - Strapi Developer Docs and there are example in docs.

// path: ./src/api/article/controllers/article.js

const { createCoreController } = require('@strapi/strapi').factories;

module.exports = createCoreController('api::article.article', ({ strapi }) =>  ({
    async create(ctx) {
        console.log(ctx)
        // you own create logic code here
        // find related article count of ctx.state.user.id, if > N then return message
    }
})
)

Hope it can help you

1 Like

Thank you so much i think it solves my problem

Sorry to disturb you but you can help me with logic because i failed when actually use the logic

const { createCoreController } = require(’@strapi/strapi’).factories;

module.exports = createCoreController(‘api::blog.blog’ , ({ strapi }) => ({

async create(ctx) {

// some logic here

const response = await super.create(ctx);

// some more logic

console.log(response , "response");

console.log(ctx.request.body.data.Related_Blogs);



const count = await strapi.db.query(ctx.request.body.data.Related_Blogs).count();

console.log(count, "ctx");

return response;

  }

}));

Hope it helps to crack the logic

I will have a try later. maybe some hours later. @Devarshivaidya

@Devarshivaidya I think the code you want to get maybe like under:

const { createCoreController } = require('@strapi/strapi').factories;

module.exports = createCoreController('api::article.article',
  ({ strapi }) => ({
    async create(ctx) {

      const response = await strapi.service('api::article.article').find({
        filters: {
          user: {   // this filter linked user, you also can use createdBy
            id: ctx.state.user.id
          }
        }
      }).then(
        res => {
          if (res.results.length >= 3) {
            return "You have already created 3 article"
          }
        }
      )

      // if not great than 3, then create article, if true return the message
      const finalRes = response ?? super.create(ctx)

      return finalRes
    }
  })
);

you can find here and run online
GavinXue/strapi-study-cases: strapi use cases when study, maybe it can help someone else.

1 Like

Ok, and the second part of the question, how to make this custom controller restriction reflected in the Strapi UI?