LoginSignup

This article is a Private article. Only a writer and users who know the URL can access it.
Please change open range to public in publish setting if you want to share this article with other users.

More than 5 years have passed since last update.

【CakePHP3】MySQL上で一括登録と更新

Last updated at Posted at 2018-03-18

CakePHP3上でのDB操作のサンプルプログラム。

一括登録と更新処理を紹介。

INSERT [一括登録]

複数件データ登録時、クエリ発行数を減らすために一括登録する手順。

namespace App\Model\Table;

use Cake\ORM\Query;
use Cake\ORM\RulesChecker;
use Cake\ORM\Table;
use Cake\Validation\Validator;

/**
 * MCompanies Model
 */
class MCompaniesTable extends Table
{    
    /**
     * 登録
     * 
     * @param array $targets
     * @return boolean
     */
    public function insert($targets)
    {
        $conn = $this->connection();
        try {
            $conn->begin();
            $query = $this->query()->insert(['company_code', 'company_name', 'is_deleted']);
            foreach ($targets as $target) {
                $query->values($target);
            }
            $query->execute();
            $conn->commit();
            return true;
        } catch (Exception $e) {
            // エラー処理
            return false;
        }
    }
}

ループ処理で登録情報をvaluesに設定し、再度に一度だけexecute実行。

定義した登録処理を呼び出す。

namespace App\Model\Table;

use Cake\Console\Shell;
use \SplFileObject;

class TestShell extends Shell
{
    public $tasks = ['Util'];

    public function initialize()
    {
        parent::initialize();
        $this->loadModel('MCompanies');
    }

    /**
     * 登録
     */
    public function insert()
    {
        // 登録データ作成
        $targets = array();
        for ($i = 1; $i < 11; $i++) {
            $targets[] = array(
                "company_code" => $i,
                "company_name" => "test",
                "is_deleted" => 0);
        }

        if ($this->MCompanies->insert($targets) === false) {
            $this->out("Failure");
            return;
        }
        $this->out("Success");
    }

}

UPDATE

更新処理は1件単位にクエリ発行する方式を記載。

namespace App\Model\Table;

use Cake\ORM\Query;
use Cake\ORM\RulesChecker;
use Cake\ORM\Table;
use Cake\Validation\Validator;

/**
 * MCompanies Model
 */
class MCompaniesTable extends Table
{   
    /**
     * 更新
     * 
     * @param array $targets
     * @return boolean
     */
    public function update($targets)
    {
        $conn = $this->connection();
        try {
            foreach ($targets as $target) {
                $company = array(
                    "company_name" => $target["company_name"],
                    "is_deleted" => $target["is_deleted"]
                );
                $condition = array("company_code" => $target["company_code"]);
                $this->updateAll($company, $condition);
            }
            $conn->commit();
            return true;
        } catch (Exception $e) {
            // エラー処理
            return false;
        }
    }
}

定義した登録処理を呼び出します。

namespace App\Shell;

use Cake\Console\Shell;
use \SplFileObject;

/**
 * Test shell command.
 */
class TestShell extends Shell
{
    public $tasks = ['Util'];

    public function initialize()
    {
        parent::initialize();
        $this->loadModel('MCompanies');
    }

    /**
     * 更新
     */
    public function update()
    {
        $targets = array();
        for ($i = 1; $i < 11; $i++) {
            $targets[] = array(
                "company_code" => $i,
                "company_name" => "xxxxxx",
                "is_deleted" => 1);
        }

        if ($this->MCompanies->update($targets) === false) {
            $this->out("Failure");
            return;
        }
        $this->out("Success");
    }

}
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