cakephp:如何为hasmany关系插入值

时间:2011-07-12 10:12:15

标签: cakephp cakephp-1.3

如何在我的上传表格中输入内容,此代码无效

这是我的项目数组:

[Project] => Array ( [name] => Testproject [description] => TestDescription [Upload] => Array ( [0] => Array ( [name] => testlink1 [Type] => link )

                        [1] => Array
                            (
                                [name] => testlink2
                                [Type] => link
                            )

                        [2] => Array
                            (
                                [name] => testlink3
                                [Type] => link
                            )

                    )

)

我写过

foreach($this->data['Project']['Upload'] as $key=>$value) 
{
    $this->data['Upload'][$key]['project_id'] = $this->Project->id; 
    $this->data['Upload'][$key]['name'] = $value['name'];
    $this->data['Upload'][$key]['type'] = $value['Type'];
    $this->data['Upload'][$key]['created'] = date("Y-m-d H:i:s"); 
    $this->data['Upload'][$key]['modified'] = date("Y-m-d H:i:s");
    $this->Project->Upload->save($this->data['Upload'][$key]);
}

1 个答案:

答案 0 :(得分:1)

你不需要foreach。只要保持真诚,你的关联是正确的:

/app/models/project.php
var $hasMany = array('Upload');

/app/models/upload.php
var $belongsTo = array('Project');

如果您拥有如上所述的数据阵列,则可以使用$this->Project->saveAll($this->data)一次保存所有内容。

查看手册以获取有关saveAll的更多信息以及如何保存相关数据:Saving related model data