カテゴリー
コンピューター

CakePHP2 でより深いアソシエーションのデータを saveAll する方法。

ポイント

  • saveAll の第2引数で、array(‘deep’ => true) を設定する。

具体例

次のような場合を考えます。

  • User hasOne Profile
  • Profile hasOne ExProfile
  • フォームで User、 Profile そして ExProfile のデータを入力します。
  • このような形のデータを保存します。
    Array
    (
        [User] => Array
            (
                [id] => 1
                [username] => adminuser
                [password] => adminuser
                [group_id] => 1
            )
    
        [Profile] => Array
            (
                [id] => 
                [catch_phrase] => アイエエエエエエエエエエエエエエ!?
                [self_introduction] => ドーモ、adminuser デス。
                [ExProfile] => Array
                    (
                        [id] => 
                        [job] => ニンジャ
                        [address] => ネオサイタマ
                    )
    
            )
    
    )

ソース

app/Controller/UsersController.php

<?php
App::uses('AppController', 'Controller');
/**
 * Users Controller
 *
 * @property User $User
 */
class UsersController extends AppController {

/**
 * edit method
 *
 * @throws NotFoundException
 * @param string $id
 * @return void
 */
	public function edit($id = null) {
		$this->User->id = $id;
		if (!$this->User->exists()) {
			throw new NotFoundException(__('Invalid user'));
		}

		if ($this->request->is('post') || $this->request->is('put')) {

			// 入力フォームの値のみを保存するため、それら以外の post データを排除する。
			$save_data['User']['id'] = $this->request->data['User']['id'];
			$save_data['User']['username'] = $this->request->data['User']['username'];
			$save_data['User']['password'] = $this->request->data['User']['password'];
			$save_data['User']['group_id'] = $this->request->data['User']['group_id'];
			$save_data['Profile']['id'] = $this->request->data['Profile']['id'];
			$save_data['Profile']['catch_phrase'] = $this->request->data['Profile']['catch_phrase'];
			$save_data['Profile']['self_introduction'] = $this->request->data['Profile']['self_introduction'];
			$save_data['Profile']['ExProfile']['id'] = $this->request->data['Profile']['ExProfile']['id'];
			$save_data['Profile']['ExProfile']['job'] = $this->request->data['Profile']['ExProfile']['job'];

			if ($this->User->saveAll($save_data, array('deep' => true))) {
				$this->Session->setFlash(__('The user has been saved'));
				$this->redirect(array('action' => 'index'));
			} else {
				$this->Session->setFlash(__('The user could not be saved. Please, try again.'));
			}
			/*
		*/
		} else {
			$this->User->recursive = 2;
			$this->request->data = $this->User->read(null, $id);
		}
		$groups = $this->User->Group->find('list');
		$this->set(compact('groups'));
	}
}

おわりに

次のページが参考になりました。「For saving a record along with its related records having hasMany association and deeper associated Comment belongsTo User data as well, the data array should be like this:」の部分です。ありがとうございます。

コメントを残す