Adding relations using lifecycle methods

System Information
  • Strapi Version: 3.4.1
  • Operating System: Docker container
  • Database: SQLite
  • Node Version: >=10.0.0
  • NPM Version: >=6.0.0
  • Yarn Version: 1.22.4

I have three content types: course, section, and lesson. My data flows like this:
course → section → lesson

I would like to automatically add a course to my lesson based on the section the lesson is assigned to, and I’m trying to do it using lifecycle methods, but am having trouble creating a relation. In my api/lessons/models/lessons.js file, I have this:

beforeSave: async (model, attrs, options) => {
    // get attached section
    const section = model.relations ? model.relations.section : null;

    // get sections course
    const courseId =
      section && section.attributes ? section.attributes.course : null;

    // assign to the lesson

    if (options.method === "insert" && courseId !== null) {
      model.set("course", courseId);
    } else if (options.method === "update" && courseId !== null) {
      attrs.course = courseId;
    }
  } 

It isn’t working, although I am successfully adding a slug to the lesson (removed the code for clarity) so I know it should be possible. What am I doing wrong?

Thanks!

Can you attach the model files, please? So I could do some local tests based on your needs.

lessons.settings.json
sections.settings.json
courses.settings.json

You can share them in PM if you don’t want to share them here.

That’s definitely possible. I think in this case your section.attributes.course doesn’t contain the course. So you should make a query to get it.