【发布时间】:2017-03-26 03:03:49
【问题描述】:
我有两个表,每个表都有自己的属性和两个链接它们的外键:
会话
- 身份证
- staff_id(主要员工)- 链接到员工表的外键
- assistant_id(次要职员)- 链接到职员表的外键
- 日期
员工
- 身份证
- user_id(链接到用户表的外键)
- 姓名
当我尝试进行查找查询以显示与其主要职员的会话时,它会在 Index.ctp 中显示助理职员。
例如,如果 ID=1 的 Session 具有 staff_id=3 和 assistant_id=null,则 Index 中的 Staff 列显示为空白。但是,如果 assistant_id=1,则显示 ID=1(助理人员)而不是 ID=3(主要人员)的人员。
在我的 SessionsTable 中,我有以下内容:
$this->belongsTo('Staff', [
'foreignKey' => 'staff_id'
]);
$this->belongsTo('Staff', [
'foreignKey' => 'assistant_id'
]);
在我的 StaffTable 中,我有以下内容:
$this->hasMany('Sessions', [
'foreignKey' => 'staff_id'
]);
$this->hasMany('Sessions', [
'foreignKey' => 'assistant_id'
]);
在我的 SessionsController 中,索引函数将以下查找请求分配给 Cake 变量:
$sessions = $this->Sessions->find('all', [
'contain' => ['Staff']
]);
在Index的ctp页面中,表格如下:
<table class="bookingsTables display" id="confirmedTable">
<thead>
<tr>
<th scope="col"><?= $this->Paginator->sort('id', 'ID') ?></th>
<th scope="col"><?= $this->Paginator->sort('staff_id', 'Primary Staff Member') ?></th>
<th scope="col"><?= $this->Paginator->sort('date', 'Date') ?></th>
<th scope="col" class="actions"><?= __('Actions') ?></th>
</tr>
</thead>
<tbody>
<?php foreach ($sessions as $session): ?>
<tr>
<td><?= h($session->id) ?></td>
<td><?= $session->has('staff') ? h($session->staff->name) : '' ?></td>
<td><?= h($session->date) ?></td>
<td class="actions">
<?= $this->Html->link(__('View'), ['action' => 'view', $session->id]) ?>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
另外关于查找查询,如果我以工作人员身份登录并查找他们是主要工作人员的所有会话,它将无法找到任何内容。
$id = $this->Auth->user('id'); //gets the id of the logged in user
$sessions = $this->Sessions->find('all', [
'contain' => ['Staff'],
'conditions' => ['user_id' => $id]
]); //find Sessions where staff_id = staff member who's logged in
或者:
$id = $this->Auth->user('id'); //gets the id of the logged in user
$sessions = $this->Sessions->find('all', [
'contain' => ['Staff', 'Staff.Users'],
'conditions' => ['Users.id' => $id]
]); //find Sessions where staff_id = staff member who's logged in
【问题讨论】:
标签: mysql cakephp cakephp-3.0