Triggering lifecycle hook between non-related content types

System Information
  • Strapi Version: 3.2.4
  • Operating System: macOS High Sierra 10.13.6
  • Database: SQLite 5.0.0, PostgreSQL 8.4.1
  • Node Version: 12.18.4
  • NPM Version: >=6.0.0
  • Yarn Version: 1.22.4

I have content types posts (like blog posts) and streaks (like a number counter) which have no relation, but both separately have a common relation to users. I want to be able to update the streaks counter whenever I create a new post.

I know there are lifecycle hooks like afterCreate, but correct me if I’m wrong, my (shallow) understanding is that lifecycle hooks can only trigger changes for the specific model of the content type it’s found in (eg lifecycle methods in ./api/{apiName}/models/post.js can only trigger changes for posts, not other content types). Is that a correct understanding? Happy to be proven wrong tbh!

So is it possible to write a method in ./api/{apiName}/models/post.js to update the streak number counter? Would be super grateful for any high level advice or tips!

Hey @jasonleow,

I’m glad I can make you happy, because you are indeed wrong on that :wink:.

You are free to do what every logic you want inside the ‘trigger’, as the examples in the docs try to displays. You can simply use the (core) controllers/services to edit any content type.
For example your ./api/post/models/post.js could look something like this:

'use strict';

module.exports = {

  lifecycles: {
    async afterCreate(result, data) {
      const id = result.streakID;
      const streak ={ id });{ id }, { counter: streak.counter++ });

I hope this helps. :+1:

Just one disclaimer: you can’t get the request context (ctx) inside the lifecycle hook.

Ooh and I didn’t test this, but something like this should work :wink:

1 Like

Thanks for clarifying! Glad to be proven wrong in this case! :wink:

1 Like