hasMany on a pivotModel

I’m using October CMS v2 and am trying to set up a hasMany relationship on a pivot table.

Here are the tables involved:
locations (facilities that tutor students)
programs (examples: reading, writing, mathematics)
location_programs (pivot table, records which programs a location offers)
location_program_sessions (hasMany table for the location_programs, records dates when each program is available, e.g., reading classes may be available March 1st to March 15th, and April 1st to April 15th, etc.)

The locations + programs + location_programs relationship is working. I can successfully assign programs to locations in the backend.

What is not working is trying to assign sessions to each location_program. Here is how I have it set up:

PivotModel

    public $hasMany = [
        'program_sessions' => [
            \MyPlugin\Base\Models\ProgramSession::class,
            'key' => 'location_program_id',
        ],
    ];

Here is the config_relation.yaml:

programs:
  pivot:
    form:
      fields:
        pivot[program_sessions]:
          prompt: Class Sessions
          type: repeater
          form:
            fields:
              id:
                label: id
                type: text
                readonly: true
                hidden: true
              start_date:
                label: 'Session Start Date'
                type: datepicker
                mode: date
              end_date:
                label: 'Session End Date'
                type: datepicker
                mode: date
                description:
              label: 'Session Description'
                type: text

As a test, I manually created a location_program_session record and gave it proper ids. When I reloaded the form, it rendered an existing repeater, but all the fields were empty. So it seems to know a record exists, but it can’t render the data from the record.

As well, if I try to set the values and save, when I stepped through I did see the data in the $_POST (I put a break in the beforeSave() method in the pivotModel), but there was no id field. So I think that may be part of the problem.

And when I try to create a new location_program_session entry, when I step through the breakpoint, the data seems to get dropped by the time it hits the deferred binding save part of the code… the pivot has no child data for the session under it like it did when examining the raw $_POST data.

Hopefully this all makes sense, thanks for your time!

Hey @Jinjo

When you start definining relations on the pivot model, you should switch it to a regular model and make it belongTo left and right; like a manual version of belongToMany.

It is some function overlap, however, belongsToMany caters mainly to basic implementations.