使用 HABTM 和 HasMany 保存数据会丢失 foreignKey

Saving data with HABTM and HasMany looses foreignKey

我有一个具有两个关系的用户模型:

  1. HasAndBelongsToMany

    public $hasAndBelongsToMany = array(
        'group' => array(
            'className' => 'group',
            'foreignKey' => 'user_id'
        )
    );
    
  2. 有很多

    public $hasMany = array(
      'phonenumber' => array(
        'className' => 'phonenumber',
        'foreignKey' => 'user_id'
      )
    );
    

电话号码和群组已设置

public $belongsTo = array(
    'User' => array(
        'className' => 'User',
        'foreignKey' => 'user_id'
    )
);

当我使用

$this->saveAll(array(
            'User' => $data, 
            'phonenumber' => $numbers, //array with data
            'group' => $groups //array with data
   )
);

数据保存在表格中,但 User_id 在电话号码和群组 table 中为“0”。

如何保存正确的 ID? (CakePHP 2.5 版)

考虑 CakePHP 文档,您会发现以下提示:

When working with associated models, it is important to realize that saving model data should always be done by the corresponding CakePHP model. If you are saving a new Post and its associated Comments, then you would use both Post and Comment models during the save operation (http://book.cakephp.org/2.0/en/models/saving-your-data.html#saving-related-model-data-hasone-hasmany-belongsto)

根据这些信息,我建议您尝试以下操作:

$this->User->save($data);  // first save the user

假设您有多个号码:

foreach($numbers as $key => $nbr) {
    // set user_id related data
    $numbers[ $key ]['Phonenumber']['user_id'] = $this->User->id;
}

最后保存你的相关数据:

$this->User->Phonenumber->saveAll($numbers);

由于此代码未经测试您可能需要进行一些调整。始终确保遵循 Cake-Conventions 并使用 CamelCase ModelNames。

FWIW saveAll() 应该 像宣传的那样工作,一举将新的 user_id 填充到子表中。

你关注过相关选项:atomic & deep吗?

特别是如果数据库不支持事务,你需要传入原子:

$this->saveAll(array(
            'User' => $data, 
            'phonenumber' => $numbers, //array with data
            'group' => $groups //array with data
   ),
   array('atomic' => false)
);