gpt4 book ai didi

mysql - CakePHP 3 - 两个外键链接到同一个表 - 使用了错误的外键

转载 作者:行者123 更新时间:2023-11-29 10:56:06 26 4
gpt4 key购买 nike

我有两个表,每个表都有自己的属性和两个链接它们的外键:

session

  • ID
  • staff_id(主要职员)- 链接到职员表的外键
  • assistant_id(二级职员)- 链接到职员表的外键
  • 日期

工作人员

  • ID
  • user_id(链接到用户表的外键)
  • 姓名

当我尝试执行“查找”查询以显示与其主要工作人员的 session 时,它会在 Index.ctp 中显示助理工作人员。

例如,如果 ID=1 的 session 的 Staff_id=3 且 Assistant_id=null,则“索引”中的“人员”列显示为空白。但是,如果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>

此外,关于查找查询,如果我以工作人员身份登录并查找他们作为主要工作人员的所有 session ,则将无法找到任何 session 。

$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

最佳答案

如果第二个实例存在,Cake 将覆盖 Staff 的第一个实例。为了避免这种情况,你的模型应该是这样的:

$this->belongsTo('Staff', [ 
'className' => 'Staff',
'foreignKey' => 'staff_id',
'propertyName' => 'staff'
]);

$this->belongsTo('Assistant', [
'className' => 'Staff',
'foreignKey' => 'assistant_id',
'propertyName' => 'assistant'
]);

然后在你的 View 中替换

<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>

关于mysql - CakePHP 3 - 两个外键链接到同一个表 - 使用了错误的外键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42997771/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com