cakePHP 2.x アソシエーションされたデータの保存 saveAllとsaveManyとsaveAssociated

Shunsuke Sawada

とりあえずsaveAllで大丈夫だけども。


Model::saveAll(array $data = null, array $options = array())

The saveAll function is just a wrapper around the saveMany and saveAssociated methods. it will inspect the data and determine what type of save it should perform. If data is formatted in a numerical indexed array, saveMany will be called, otherwise saveAssociated is used. This function receives the same options as the former two, and is generally a backwards compatible function. It is recommended using either saveMany or saveAssociated depending on the case.

saveAllはsaveManyとsaveAssociatedを包括してるから、どっちか勝手に実行してくれるけど、なるべくなら状況に合わせてsaveManyかsaveAssociatedを使ったほうがいいよ。
オプションはまったく同じものを取る。

validate: Set to false to disable validation, true to validate each record before saving, ‘first’ to validate all records before any are saved (default)

atomic: If true (default), will attempt to save all records in a single transaction. Should be set to false if database/table does not support transactions.

fieldList: Equivalent to the $fieldList parameter in Model::save()

deep: (since 2.1) If set to true, not only directly associated data is saved, but deeper nested associated data as well. Defaults to false.

アソシエーションされているモデルが更にアソシエーションされている場合、deepオプションをtrueにしましょう。

$Article->saveAll($data, array('deep' => true));

Shunsuke Sawada

おすすめの記事

CakePHP 2.x JSヘルパーでajax通信(ajax helperは使わない)
20
Rails4でQiita投稿ボタンをつくった
18
紙のデザイナーがウェブ開発できるようになるまでに必要なこと
451