Quantcast
Channel: Plamo Linux 日記
Viewing all articles
Browse latest Browse all 675

cakephp3 で複数データの insert 時の created / modified 処理

$
0
0

たまに書いてる cakephp の話題.

cakephp3 で複数データを一気に保存したいときの処理の話を少し.

cakephp3 からは saveAll がなくなったみたいですね.で,cookbook を見ると insert を使って

$query = $articles->query();
$query->insert(['title', 'body'])
    ->values([
         'title' => 'First post',
        'body' => 'Some body text'
    ])
    ->values([
        'title' => 'Second post',
        'body' => 'Another body text'
    ])
    ->execute();

な感じでやればオッケーみたい.ということでやってみたら,Table 定義に

$this->addBehavior('Timestamp');

してても created / modified フィールドのタイムスタンプが 0000-00-00 00:00:00 になってしまいますね.
仕方がないので自前で

$query = $articles->query();
$query->insert(['title', 'body', 'created', 'modified'])
    ->values([
        'title' => 'First post',
        'body' => 'Some body text',
        'created' => date('Y-m-d h:m:s'),
        'modified' => date('Y-m-d h:m:s')
    ])
    ->values([
        'title' => 'Second post',
        'body' => 'Another body text',
        'created' => date('Y-m-d h:m:s'),
        'modified' => date('Y-m-d h:m:s')
    ])
    ->execute();

としたら日付は入るようになりました.ほかに何かスマートな方法はあるのかなぁ?

まぁ,とりあえず思い通りにはなったので当面はこれでオッケーとするか.

追記)

もうちょっと調べてみたら

Cake\ORM\Table::saveMany($entities, $options = [])

ってのがありましたね.ということで,

$data = [
    [
        'title' => '一番目の投稿',
        'published' => 1
    ],
    [
        'title' => '二番目の投稿',
        'published' => 1
    ],
];
$articles = TableRegistry::get('Articles');
$entities = $articles->newEntities($data);
$result = $articles->saveMany($entities);

な感じで良いみたいですね.失礼しました.

でも,この方法だと insert が複数回実行されるのがちょっと気になるかな.

前述の $query->insert() を使う方法だと insert 一発で実行されますね.

まぁ,用途によって使い分ける感じにすれば良いですかね.


Viewing all articles
Browse latest Browse all 675

Trending Articles