Hi folks,
I’m new to Cake and am trying to work with my first belongsToMany “through” relation in CakePHP 3.4. I’m trying to figure out how to access the “through” relation data in my view.
Here’s the general setup:
Women hasMany Roles
Women belongsToMany Convents through Roles
In my Template/Women/view.ctp I want to be able to show her roles as well as the names of the convents she’s associated with. The “Roles” table includes woman_id, convent_id, and her role in the convent. So the scafffolded version fresh out of the oven does this:
<?php foreach ($woman->roles as $roles): ?>
<tr>
<td><?= h($roles->id) ?></td>
<td><?= h($roles->woman_id) ?></td>
<td><?= h($roles->convent_id) ?></td>
<td><?= h($roles->role) ?></td>
What I’m trying to do is to show the name of the convent instead of its ID. I can get it with a rather hack-y approach:
$convents = $woman->convents;
foreach ($convents as $convent) {
if ($convent->id == $curr_convent_id) {
$convent_name = $convent->name;
}
But I’m pretty sure that makes me a bad person and is not the right/Cake way to do it. I rather wonder if I’m doing too much in the view here and should be doing more in the controller, but I don’t know.
I thought I might be able to use
convents->find($curr_convent_id)
but the find method wasn’t available on that object.
I also tried calling
$roles->convent->name
but it turns out that $roles->convent
returns NULL
.
I would appreciate any suggestions and especially a pointer to tutorial or code example that shows more about working with “through” relations. The Documentation talks about them in the Models section, but I didn’t find more in the Views sections.
Here’s the page I’m working on:
https://wittprojects.net/thru/women/view/3
And the GitHub repo:
Thanks!