0

I have 2 tables associated as belongsToMany, scouts and merit_badges. I also have data in the join table that I need to access so the relationship options is set as 'through'

e.g. in ScoutsTable.php

$this->belongsToMany('MeritBadges', [
        'through' => 'MeritBadgesScouts'
    ]);

Additional I have made use of tree behavior in the merit_badges table, since some merit_badges have dependencies. So, the merit_badges table has a column parent_id.

I'm working on a view in scouts that lists all of the associated merit_badges and I'd like to show the name of the merit_badges parent merit_badge, but I'm having trouble getting it to return that value.

Briefly, here is what I have in the template.

<?php foreach ($scout->merit_badges as $meritBadges): ?>
        <tr>
            <td><?= h($meritBadges->name) ?></td>
            <td><?= $meritBadges->has('parent_merit_badge') ? $meritBadges->parent_meritbadge->name : '' ?></td>
        </tr>
?>

The 'has('parent_merit_badge')' returns false, so I'm assuming I need to add something to the ScoutTable model to get this to work, but I'm having trouble figuring out what. This is CakePHP 3.5, btw. Thanks

Drew
  • 1
  • 2

1 Answers1

0

The issue was not in the Model, but in the controller for the this template. I needed to pass the ParentMeritBadges model to template as below.

public function view($id = null)
{
    $scout = $this->Scouts->get($id, [
        'contain' => ['MeritBadges', 'MeritBadges' => ['ParentMeritBadges']]
    ]);

    $this->set('scout', $scout);
}

Once this is done the following worked.

<?php foreach ($scout->merit_badges as $meritBadges): ?>
        <tr>
            <td><?= h($meritBadges->name) ?></td>
            <td><?= $meritBadges->has('parent_merit_badge') ? $meritBadges->parent_merit_badge->name : '' ?></td>
        </tr>
?>
Drew
  • 1
  • 2