環境
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
)
)
)
*/
}
}