Cakephp保存与belongs_to和has_many关系中的模型相关联

时间:2014-06-06 09:33:14

标签: cakephp

使用cakephp,我有模型机构,地址和用户。关系是:

An Institution has_many Addresses, Users.
An User belongs_to Address, Institution.
An Address belongs_to an Institution and has_many Users;

创建机构时,还应保存地址和用户。 所以在Institution控制器的add方法中我尝试了以下内容:

if ($this->Institution->saveAssociated($this->request->data)) {
            // set Users default address to institutions initial address
            $this->User->set(array(
                'address_id' => $this->Address->id
            ));
            $this->User->save();
            $this->Session->setFlash(__('The institution has been saved.'));
            return; //$this->redirect(array('action' => 'index'));
}

但这会给我Error: SQLSTATE[HY000]: General error: 1364 Field 'address_id' doesn't have a default value,因为address_id不能是NULL。它适用于某些系统,有些则不适用。

请求数据如下所示

array(
'Institution' => array(
    'name' => 'name1',
    'country_id' => '83',
    'sigil' => 'sig1',
    'count_media_down' => '0'
),
'Address' => array(
    (int) 0 => array(
        'street' => 'street1',
        'zipcode' => '12345',
        'city' => 'city1',
        'is_default' => true,
        'country_id' => '83'
    )
),
'User' => array(
    (int) 0 => array(
        'password' => '*****',
        'username' => 'user1',
        'email' => 'email@email.com',
        'first_name' => 'first1',
        'last_name' => 'last1',
        'department' => 'dep1',
        'language' => 'de',
        'role' => 'exchanger'
    )
)
)

我怀疑这是has_many和belongs_to用户冲突的问题。 解决这个问题的正确方法是什么?

0 个答案:

没有答案