LoginSignup
0
2

More than 3 years have passed since last update.

🍰【CakePHP2】Controllerで動的に一時テーブルを作成し使用する方法

Last updated at Posted at 2020-07-15

環境

PHP 7.2.21
CakePHP 2.10.18
MySQL 5.7.27

やりたいこと

テンポラリテーブルを使いたい

やったこと

ModelをuseTable = falseで用意してControllerでテーブル作成しセット

Model

TemporaryTable.php
<?php

App::uses('AppModel', 'Model');

class TemporaryTable extends AppModel
{
    public $useTable    = false;
    public $primaryKey  = '';
    public $useDbConfig = '';

    function setSource($tableName) {
        $this->setDataSource($this->useDbConfig);
        $db = ConnectionManager::getDataSource($this->useDbConfig);
        $db->cacheSources = ($this->cacheSources && $db->cacheSources);

        $this->table = $this->useTable = $tableName;
        $this->tableToModel[$this->table] = $this->alias;
        $this->schema();
    }
}

Controller

HogeController.php
<?php

class HogeController extends AppController {
    public function index() {
        // TEMPORARY TABLE名
        $tempTableName = 'temporary_table';
        // database.phpのDBconfigをModelに設定
        $this->TemporaryTable->useDbConfig = 'admin';
        // TEMPORARY TABLEを作成
        $this->TemporaryTable->query('CREATE TEMPORARY TABLE ' . $tempTableName . ' (id INT(11), name VARCHAR(256));');
        // 作成したTEMPORARY TABLE名をModelに設定
        $this->TemporaryTable->useTable = $tempTableName;

        // 先ずfindしてみる -> result:array(0)
        $data = $this->TemporaryTable->find('all');

        // テストデータをsaveする
        $testData = [
            'id'   => '1',
            'name' => '_test',
        ];
        $this->TemporaryTable->create();
        $this->TemporaryTable->save($testData);
        // テストデータ2をsaveする
        $testData2 = [
            'id'   => '2',
            'name' => 'test_test',
        ];
        $this->TemporaryTable->create();
        $this->TemporaryTable->save($testData2);
        // 再度find -> result:array(2)
        $data = $this->TemporaryTable->find('all');
        var_dump($data);
        /* find結果
            Array
            (
                [0] => Array
                    (
                        [TemporaryTable] => Array
                            (
                                [id] => 1
                                [name] => _test
                            )
                    )
                [1] => Array
                    (
                        [TemporaryTable] => Array
                            (
                                [id] => 2
                                [name] => test_test
                            )
                    )
            )
        */
    }
}
0
2
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
2