Get Related Record ID Value

Hello guys,

I’m using CakePHP 5. I have a few tables:

  1. Webs (id)
  2. Audits (id, web_id, session_id, user_id)
  3. Sessions (id, name)
  4. Users (id, fullname)

When I open web views, for example …/webs/view/1, it will show the related audits. In the related audit (view in webs), it has user_id and session_id, which show the number, e.g., user_id == 1 and session_id == 1. The user table has a fullname column, and the session table has a name column. How can I render the fullname and session name in the related record view on the web view?

Thank you, and I appreciate any assistance from the forum members.

you just output the field you want in the associated records.

bin/cake bake all --everything generates something like this:

<div class="related">
    <h4><?= __('Related Sessions') ?></h4>
    <?php if (!empty($web->sessions)) : ?>
    <div class="table-responsive">
        <table>
            <tr>
                <th><?= __('Id') ?></th>
                <th><?= __('Name') ?></th>
                <th><?= __('Created') ?></th>
                <th><?= __('Modified') ?></th>
                <th class="actions"><?= __('Actions') ?></th>
            </tr>
            <?php foreach ($web->sessions as $session) : ?>
            <tr>
                <td><?= h($session->id) ?></td>
                <td><?= h($session->name) ?></td>  // <=========
                <td><?= h($session->created) ?></td>
                <td><?= h($session->modified) ?></td>
                <td class="actions">
                    <?= $this->Html->link(__('View'), ['controller' => 'Sessions', 'action' => 'view', $session->id]) ?>
                    <?= $this->Html->link(__('Edit'), ['controller' => 'Sessions', 'action' => 'edit', $session->id]) ?>
                    <?= $this->Form->postLink(__('Delete'), ['controller' => 'Sessions', 'action' => 'delete', $session->id], ['confirm' => __('Are you sure you want to delete # {0}?', $session->id)]) ?>
                </td>
            </tr>
            <?php endforeach; ?>
        </table>
    </div>
    <?php endif; ?>
</div>

$web->sessions contains all the associated Sessions records which are mapped to your current web entry. This automatically happens if you do $this->Webs->get($id, ['contain' => ['Sessions']]) inside your controller action - its called Eager Loading

$session inside the foreach is just an entity of type App\Model\Entity\Session and therefore represents the associated record in your current web entry.

Sorry for the late reply. Thanks for the solution. It solved my problem. Here i share the solution:

webs controller (view):

...
$web = $this->Webs->get($id, [
            'contain' => ['Audits' => ['Users', 'Sessions']],
        ]);

in webs view related:

<?php foreach ($web->audits as $audits) : ?>
<tr>
<td><?= h($audits->session_id) ?>: <?= h($audits->session->name) ?></td>
<td><?= h($audits->user->fullname) ?></td>
...