【CakePHP3】異なるテーブル間でデータをコピーする!
CakePHP3で、あるテーブルのデータを別のテーブルにコピーする形でセーブする方法です。
以下、「Draft_posts」テーブルのデータを「Posts」テーブルにコピーしています。
(※この二つのテーブルは全く同じ構造をしています)
try{
//コピー元のデータを取得
$post = $this->Draft_posts->find()->where(['post_id' => 1234])->first();
//セーブ!
$entity = $this->Posts->newEntity();
$entity = $this->Posts->patchEntity($entity, $post->toArray());
$ret = $this->Posts->save($entity);
if (!$ret){
throw new Exception();
}
} catch (Exception $ex) {
//エラー時
$this->log("cannot copy data:".$ex->getMessage(), "debug");
}以上!