0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

🍰【CakePHP2】配列で指定した値に対してINまたはNOT INの複数件アップデートを行う

Last updated at Posted at 2020-01-08

環境

PHP 7.2.21
CakePHP 2.10.18
MySQL 5.7.27

やりたいこと

CakePHP2のupdateAll()を用いると条件式や任意のSQLにてbulk updateができますが
配列になっている値をカラム指定してINやNOT INで指定してupdateを行う方法を試したい

やったこと

updateAll()の第一引数は配列にて「'カラム名' => 値」のSET句を指定
INの第二引数は「'カラム名' => 更新対象」を指定する
NOT INの場合は'NOT' => の配列にして条件を一段ネスト

尚、modifiedは自動で更新されないのでこちらも必要に応じて第一引数に追加してやります

更新するテーブル(Hogehoge)

id content del_flg modified
1 'test' 0 '2020-01-08 10:00:00'
2 'neko' 0 '2020-01-08 11:00:00'
3 'hoge' 0 '2020-01-08 12:00:00'
4 '🐈🐈🐈' 0 '2020-01-08 13:00:00'
5 'くぃいた' 0 '2020-01-08 14:00:00'

IN

HogeController.php
    // 対象のIDをINで更新するパターン
    private function updateByIdIN() {
        $updateIdArray = ['1', '2', '3'];

        $this->Hogehoge->updateAll(
            [
                'del_flg'  => 1,
                'modified' => 'NOW()',
            ],
            [
                'id' => $updateIdArray
            ]
        );
    }

NOT IN

HogeController.php
    // ↑とは逆に対象のIDのNOT INで更新するパターン
    private function updateByIdNOTIN() {
        $updateIdArray = ['1', '2', '3'];

        $this->Hogehoge->updateAll(
            [
                'del_flg'  => 1,
                'modified' => 'NOW()',
            ],
            [
                'NOT' => [
                    'id' => $updateIdArray
                ]
            ]
        );
    }

結果

それぞれ配列内のIDが対象に更新される

IN

id content del_flg modified
1 'test' 1 '2020-01-08 17:00:00'
2 'neko' 1 '2020-01-08 17:00:00'
3 'hoge' 1 '2020-01-08 17:00:00'
4 '🐈🐈🐈' 0 '2020-01-08 13:00:00'
5 'くぃいた' 0 '2020-01-08 14:00:00'

NOT IN

id content del_flg modified
1 'test' 0 '2020-01-08 10:00:00'
2 'neko' 0 '2020-01-08 11:00:00'
3 'hoge' 0 '2020-01-08 12:00:00'
4 '🐈🐈🐈' 1 '2020-01-08 17:00:00'
5 'くぃいた' 1 '2020-01-08 17:00:00'
0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?