CakePHP - 复杂的关联

时间:2013-08-22 14:46:38

标签: cakephp-2.0

我是新蛋糕PHP,我有一些问题

有三种型号:Guardian,Student和StudentFee。

关系看起来像这样:Guardian有很多学生,学生有很多学生,StudentFee属于Guardian,学生。

我的问题是除了插入学生和监护人的详细信息之外,没有插入StudentFee详细信息。

我的模特就像

class Guardian extends AppModel {
    public $name = 'Guardian';

    public $recursive =2;
    public $hasMany = array(
            'Student' => array(
                'className'     => 'Student',
                'dependent'     => true
            )
    );

}

class Student extends AppModel {
    public $name = 'Student';

        public $hasMany = array(
            'StudentFee' => array(
                'className'     => 'StudentFee',
                'dependent'     => true
            )

    );
}

class StudentFee extends AppModel {
    public $name = 'StudentFee';
    public $belongsTo = array(
                    'Guardian' => array(
                    'className'     => 'Guardian',
                    'dependent'     => true
            ),
                'Student' => array(
                    'className'     => 'Student',
                    'dependent'     => true
            )
    );
}

在我的控制器中,我使用了saveAssociated(),如下面的代码

$this->Guardian->set($this->request->data);
$this->Guardian->saveAssociated($this->Guardian->data, array('validate' => false)); 

请帮助解决此问题,在此先感谢。

1 个答案:

答案 0 :(得分:0)

对我来说是正确的:

模型

// Guardian
    $hasMany = array(
      'Student' => array('clasName' => 'Student', 'foreignKey' => 'guardian_id')
    );

// Student
    $belongsTo = array(
      'Guardian' => array('clasName' => 'Guardian', 'foreignKey' => 'guardian_id')
    );

    $hasMany = array(
      'StudentFee' => array('clasName' => 'StudentFee', 'foreignKey' => 'student_id')
    );

// StudentFee
    $belongsTo = array(
      'Student' => array('clasName' => 'Student', 'foreignKey' => 'student_id')
    );

您的数据(POST)可能就是这样:

[Guardian] => array(
),
['Student'] => array(
  [0] => array(
    ['StudentFee'] => array(
    )
  ),
  [1] => array(
    ['StudentFee'] => array(
    )
  )
)

所以,只需保存:

// use the deep option to save items after the second level
$this->Guardian->saveAssociated($this->request->data, array('deep' => true));

我希望这对你有所帮助。 请尝试,如果有效,请告诉我。