CakePHP 2.1 - 保存(和创建)多个Join模型和相关模型

时间:2012-03-06 02:40:41

标签: cakephp

我的模型关系如下:

Student hasMany ClassStudent
Class hasMany ClassStudent
ClassStudent belongsTo Student
ClassStudent belongsTo Class
ClassStudent is a join model.

我想要做的是创建学生,使用现有的课程或创建一个新的课程,并创建一个连接学生和课程的连接模型记录。

我想在一次保存中调用(如果可能的话)。

我试过了:

$data = array(
    'Student' => array(
        '0' => array( ... ), // Data in here
        '1' => array( ... ),
        ...,
        'n' => array( ... )
    ),
    'Class' => array(
        'class_id' => x // The class that I want the above students to be associated with
    )
)

我想要做的是创建n个学生记录,并将它们添加到一个类中(如果用户想要添加一个新类,可能同时创建一个类)。我还想在创建学生记录时为每个学生创建一个连接模型记录。

这可能吗?我正在使用Cake 2.1.0(今天的稳定版),我尝试了使用$ options ['deep'] = true的不同类型的saveAll(saveAssociated和saveMany)。

我的数据阵列可能格式不正确吗?

修改 我也尝试过:

$data = array(
    'ClassStudent' => array(
        '0' => array(
            'Student' => array (...), // Data
            'Class' => array(id => x) // The id of the Class the Student should be associated to
        ...,
        'n' => array(
            'Student' => array(...), // n-th Student
            'Class' => array(id => x)
     )
 );

$this->saveAll($data['ClassStudent'], array('deep' => true));

在上述情况下,它在学生表中成功创建了新的学生记录,但在联接表中没有创建任何内容。

1 个答案:

答案 0 :(得分:-1)

saveAll(saveAll是saveMany和saveAssociated的包装器)是该作业的正确工具。看看saveAll的文档,我没有看到有关它的任何注释更改为2.1。花了更多时间阅读,这里有一些想法

首先,你的数组结构中是否有一个类型。

'Class' => array ( 'class_id' => x )

如果已经定义了Class并且您只想添加学生,那么它将是

'ClassStudent' => array( 'class_id' => x )

话虽如此,CakesPHP ORM应该允许你使用数字索引在hasMany上使用saveAll,所以如果假设你有拼写错误,那么以下内容可能会对你有用

$data = array(
    'Student' => array(
        '0' => array( ... ), // Data in here
        '1' => array( ... ),
        ...,
        'n' => array( ... )
     ),
    'ClassStudent' => array(
        'class_id' => x // The class that I want the above students to be associated with
    )
)
$this->ClassStudent->saveAll($data);