我有两个表,每个表都有自己的属性,并有两个外键链接它们:
会话
员工
当我尝试执行查询查询时,要显示与其主要工作人员的会话,它会在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']
]);
在索引的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
答案 0 :(得分:1)
如果第二个存在,Cake将覆盖Staff的第一个实例。为避免这种情况,您的模型应该是:
$this->belongsTo('Staff', [
'className' => 'Staff',
'foreignKey' => 'staff_id',
'propertyName' => 'staff'
]);
$this->belongsTo('Assistant', [
'className' => 'Staff',
'foreignKey' => 'assistant_id',
'propertyName' => 'assistant'
]);
然后在您的视图中替换
<td><?= $session->has('staff') ? h($session->staff->name) : '' ?></td>
使用:
<td><?= $session->has('staff') ? h($session->staff->name) : $session->has('assistant') ? h($session->assistant->name) : '' ?></td>