0

我正在尝试在数组中插入一个包含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']);

该代码有效,但这是一个好方法吗?

4

1 回答 1

1

到目前为止,您的解决方案很好。

foreach ($this->request->data['Venue'] as &$venue) {
  $venue['architect_id'] = $this->Architect->id;
}

也应该工作。自己决定,你觉得哪一个更易读。

于 2012-04-21T00:08:23.110 回答