Mysql CakePHP 3-两个外键链接到同一个表-使用了错误的外键
我有两个表,每个表都有自己的属性,并且有两个外键链接它们: 会话Mysql CakePHP 3-两个外键链接到同一个表-使用了错误的外键,mysql,cakephp,cakephp-3.0,Mysql,Cakephp,Cakephp 3.0,我有两个表,每个表都有自己的属性,并且有两个外键链接它们: 会话 身份证 staff_id(主要工作人员)-外键链接到staff表 助手id(辅助职员)-外键链接到职员表 日期 员工 身份证 用户id(外键链接到用户表) 名字 当我尝试执行查找查询时,为了显示与其主要工作人员的会话,它会在Index.ctp中显示助理工作人员 例如,如果ID=1的会话有staff_ID=3和assistant_ID=null,则索引中的staff列显示为空。但是,如果助理id=1,则显示id=1的员工(助
- 身份证
- staff_id(主要工作人员)-外键链接到staff表
- 助手id(辅助职员)-外键链接到职员表
- 日期
- 身份证
- 用户id(外键链接到用户表)
- 名字
$this->belongsTo('Staff', [
'foreignKey' => 'staff_id'
]);
$this->belongsTo('Staff', [
'foreignKey' => 'assistant_id'
]);
$this->hasMany('Sessions', [
'foreignKey' => 'staff_id'
]);
$this->hasMany('Sessions', [
'foreignKey' => 'assistant_id'
]);
在我的员工表中,我有以下内容:
$this->belongsTo('Staff', [
'foreignKey' => 'staff_id'
]);
$this->belongsTo('Staff', [
'foreignKey' => 'assistant_id'
]);
$this->hasMany('Sessions', [
'foreignKey' => 'staff_id'
]);
$this->hasMany('Sessions', [
'foreignKey' => 'assistant_id'
]);
在my SessionController中,index函数将以下查找请求分配给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', 'Staff.Users'],
'conditions' => ['Users.id' => $id]
]); //find Sessions where staff_id = staff member who's logged in
如果存在第二个实例,Cake将覆盖第一个实例。要避免这种情况,您的模型应如下所示:
$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>
与:
这不起作用,问题是别名必须是唯一的,您不能对两个关联使用Staff
,其中一个应命名为Assistant
,这也将自动确保属性名称的唯一性。类似地,StaffTable
中的关联也需要重命名。感谢ndm,编辑了我的答案以更正唯一的名称。这可以显示助手,但不能显示主要员工。在Cake变量中,会话将包含助手而不是职员。我想达到相反的效果。对不起,这是在你更新答案之前发表的评论。现在我得到了一个错误:注意(8):尝试获取非对象的属性。
即使staff_id的值不为null,这也是如此。在包含中,您需要添加助手可能的重复项