Octobercms: Many to many relations not showing

- 1 answer

Ad

I have 2 models that are many to many related.

Workshop

public $belongsToMany = [
  'registrations' => [
    'Wooltown\Events\Models\Registration',
      'table' => 'wooltown_events_registration_workshop',
      'count' => true,
  ],
];

Registration

public $belongsToMany = [
  'workshops' => [
    'Wooltown\Events\Models\Workshop',
      'table' => 'wooltown_events_registration_workshop',
      'count' => true,
  ],
];

I'm fetching a record like this:

$vars['registration'] = Registration::with('workshops')->find($registration->id);

I'm expecting an array of all associated workshops (in this case 2) in the result but the workshops array only shows me this:

...
"workshops": [{
    "registration_id": 113,
    "count": 2,
    "pivot": {
        "registration_id": 113
    }
}]
...

What am I missing here? How do I get a collection of the associated workshop models?

Ad

Answer

Ad

You should use the counter as a separate relation:

public $belongsToMany = [
    'workshops' => [
        'Wooltown\Events\Models\Workshop',
        'table' => 'wooltown_events_registration_workshop',
    ],
    'workshops_count' => [
        'Wooltown\Events\Models\Workshop',
        'table' => 'wooltown_events_registration_workshop',
        'count' => true,
    ],
];
Ad
source: stackoverflow.com
Ad