Я создал форму, где мне нужно отобразить таблицу, для которой данные поступают из двух разных таблиц. Данные поступают из таблицы филиалов. Эта таблица Branch содержит внешний ключ PrimaryContactID (int), который будет содержать первичный ключ таблицы Employee.
Теперь на странице индекса у меня отображаются все детали из таблицы Branch, за исключением PrimaryContactID. Вместо этого мне нужно отобразить имена из этой таблицы. Вот как я пытался:
controller:
public function index()
{
$branch = $this->paginate($this->Branch);
$this->set(compact('branch'));
$this->set('_serialize', ['branch']);
}
index.ctp:
<div class="branch index large-9 medium-8 columns content">
<h3><?= __('Branch') ?></h3>
<table cellpadding="0" cellspacing="0">
<thead>
<tr>
<th><?= $this->Paginator->sort('BranchID') ?></th>
<th><?= $this->Paginator->sort('BranchName') ?></th>
<th><?= $this->Paginator->sort('BranchCode') ?></th>
<th><?= $this->Paginator->sort('Telephone') ?></th>
<th><?= $this->Paginator->sort('PrimaryContactID') ?></th>
<th class="actions"><?= __('Actions') ?></th>
</tr>
</thead>
<tbody>
<?php foreach ($branch as $branch): ?>
<tr>
<td><?= $this->Number->format($branch->BranchID) ?></td>
<td><?= h($branch->BranchName) ?></td>
<td><?= h($branch->BranchCode) ?></td>
<td><?= h($branch->Telephone) ?></td>
<td><?= $this->Number->format($branch->PrimaryContactID) ?></td>
<td class="actions">
<?= $this->Html->link(__('View'), ['action' => 'view', $branch->BranchID]) ?>
<?= $this->Html->link(__('Edit'), ['action' => 'edit', $branch->BranchID]) ?>
<?= $this->Form->postLink(__('Delete'), ['action' => 'delete', $branch->BranchID], ['confirm' => __('Are you sure you want to delete # {0}?', $branch->BranchID)]) ?>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<div class="paginator">
<ul class="pagination">
<?= $this->Paginator->prev('< ' . __('previous')) ?>
<?= $this->Paginator->numbers() ?>
<?= $this->Paginator->next(__('next') . ' >') ?>
</ul>
<p><?= $this->Paginator->counter() ?></p>
</div>
</div>
Используя вышеупомянутый метод, я мог бы получить PrimaryContactID (int). Но вместо этого мне нужно получить имя из таблицы Employee. Я не знаю, как это сделать. Может кто-нибудь сказать, что я должен изменить, чтобы я получил имя?
Это очень просто, добавьте в контроллер:
$this->paginate = [
'contain' => ['Employee'] // Employees?
];
$branch = $this->paginate($this->Branch);
и по вашему мнению:
<?= h($branch->employee->name) ?>
In User.php Model first make association rule according to the requirement
eg
public $belongsTo = array(
'Profile' => array(
'className' => 'Profile',
'foreignKey' => 'user_id',
'conditions' => '',
'fields' => '',
'order' => ''
));
/// in UsersController.php
function index(){
$this->paginate = [
'contain' => ['Profiles']
];
$users = $this->paginate($this->Users);
$this->set(compact('users));
//in Users/index.ctp
foreach($users as $user)
{
echo $user['Profile']['your_field_name'];
}