我在编辑联接表的额外字段的关联数据时遇到麻烦。我有这个:
$brigada = $this->Brigadas
->findById($id)
->contain(['Tags', 'Voluntarios']) // load associated Voluntarios
->firstOrFail();
if ($this->request->is(['patch', 'post', 'put'])) {
$this->Brigadas->patchEntity($brigada, $this->request->data, ['associated' => ['Voluntarios._joinData']]);
if ($this->Brigadas->save($brigada)) {
$this->Flash->success(__('Your team data has been updated.'));
return $this->redirect(['action' => 'view', $id]);
}
$this->Flash->error(__('Unable to update your team data.'));
}
我的问题是这样的:我能够通过一个名为Participaciones的表为每个brigada加载相关的自愿性信息,该表基本上是一个联接表,带有一个名为 liders 的额外字段,该字段确定自愿性是否为该团队的团队负责人。一切都很好,就像加载布尔字段一样。
<?php for ($i = 0; $i < count($brigada->voluntarios); ++$i):
$voluntario = $brigada->voluntarios[$i];
echo $this->Form->control(
'voluntarios.' . $i . '._joinData.lider',
[
'label' => $voluntario->full_name,
]
);
endfor ?>
哪个效果很好。我的问题出在我保存时,因为它没有记录任何内容。我已经为此工作了好几天,但无济于事的唯一线索是:https://github.com/cakephp/cakephp/issues/6100。如果添加推荐的代码段$this->request->data['voluntarios'] = array_values($this->request->data['voluntarios']);
,则可以保存!但是作为交换,它基本上将我所有关联的数据都转换为空。我(非常有限的)编程经验使我相信_joinData的设置方式与我可能需要进行单独转换才能保存之间存在差异,但是我走到了穷途末路,我无处可去。有人可以帮我结束我的痛苦吗? :)
答案 0 :(得分:0)
最后,我要做的是适应上面提出的解决方案,即在控制器中手动设置所有内容。形式如下:
// https://stackoverflow.com/questions/47924459/cakephp-3-belongstomany-with-joindata
$this->request->data['voluntarios'] = [
['id' => '1', '_joinData' => ['lider' => '0']],
];
一个痛苦的嵌套答案。为什么需要手动进行此操作击败了我,但至少可以奏效。我希望有人觉得这有用。
if (!empty($this->request->data['voluntarios']['_ids'])) {
$vol = [];
foreach ($this->request->data['voluntarios']['_ids'] as $key=>$locationId) {
$lider = $this->Brigadas->Participaciones->find()
->select(['voluntario_id','lider'])
->hydrate(false)
->where(['voluntario_id' => $locationId, 'brigada_id' => $id])
->first();
$vol[] = [
'id' => (string)($key+1),
'_joinData' => [
'lider' => isset($this->request->data['voluntarios'][$key]['_joinData']['lider']) ? $this->request->data['voluntarios'][$key]['_joinData']['lider'] : false
]
];
}
}
$this->Brigadas->patchEntity($brigada, $this->request->data);
if ($this->Brigadas->save($brigada)) {
$this->Flash->success(__('Your team data has been updated.'));
return $this->redirect(['action' => 'view', $id]);
}
$this->Flash->error(__('Unable to update your team data.'));
}