我正在尝试为数组中的关系数据插入一个包含id
的数组元素,保存CakePHP
中的多个记录。
这是阵列的显示方式:
[Venue] => Array (
[0] => Array (
[name] => Great mansion
[where] => New York
)
[1] => Array (
[name] => Diamond palace
[where] => London
)
[2] => Array (
[name] => Palazzo Falcone
[where] => Bologna
)
)
我想将architect_id
添加到数组的每个元素,所以:
[Venue] => Array (
[0] => Array (
[name] => Great mansion
[where] => New York
[architect_id] => 33
)
[1] => Array (
[name] => Diamond palace
[where] => London
[architect_id] => 33
)
[2] => Array (
[name] => Palazzo Falcone
[where] => Bologna
[architect_id] => 33
)
)
我不确定我写的内容是否已优化或可以改进:
$tot = count($this->request->data['Venue']);
for ($i = 0; $i < $tot; $i ++) {
$this->request->data['Venue'][$i]['architect_id'] = $this->Architect->id;
}
$this->Venue->saveAll($this->request->data['Venue']);
代码有效,但这是一个很好的方法吗?
答案 0 :(得分:1)
到目前为止你的解决方案还不错。
foreach ($this->request->data['Venue'] as &$venue) {
$venue['architect_id'] = $this->Architect->id;
}
也应该工作。决定你自己,哪一个你觉得更具可读性。