CakePHP中的模式迁移,无需更改模式即可插入更多默认数据

时间:2019-06-12 09:09:50

标签: php cakephp data-migration

我正在使用CakePHP 2的最新版本,并希望使用控制台模式迁移工具创建模式。我还想用默认值填充数据库。到目前为止,这是可行的。

但是,我们的数据库需要不断地进行进一步的设置,这些设置存储在数据库中,并且可以单独更改。因此可能发生的是,我们的数据库结构保持不变,但例如更新时,将另外10个默认设置插入数据库。

如何在不更新架构本身的情况下使用Console/cake schema update插入语句?

这是我的主意。首先创建工资表工资表。然后在after函数中,调用函数initWageCosts(),该函数具有一个包含初始数据的数组。函数initWageCost调用函数insertData(),该函数负责检查数据是否已在数据库中。如果没有此数据集,则应插入数据。到目前为止有效。

在新的Update中,我想使用第二个数据集扩展初始数据而不更改架构。如何在不更改架构的情况下调用Console/cake schema update并调用函数initWageCosts()。我认为将其放到after函数中就足够了,但是只要不进行模式更新就不会发生任何事情。

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

class AppSchema extends CakeSchema {

public function before($event = array()) {
    $db = ConnectionManager::getDataSource($this->connection);
    $db->cacheSources = false;
    return true;
}

public function after($event = array()) {
    $this->initWageCosts();
}

public $wage_costs = array(
    'id' => array('type' => 'string', 'null' => false, 'default' => null, 'length' => 36, 'collate' => 'utf8_general_ci', 'charset' => 'utf8', 'key' => 'primary'),
    'type' => array('type' => 'string', 'null' => false, 'default' => null, 'length' => 50, 'collate' => 'utf8_general_ci', 'charset' => 'utf8'),
    'start' => array('type' => 'date', 'null' => false, 'default' => null),
    'multiplier' => array('type' => 'float', 'null' => false, 'default' => null, 'length' => '6,4', 'unsigned' => false),
    'modified' => array('type' => 'timestamp', 'null' => false, 'default' => null),
    'created' => array('type' => 'datetime', 'null' => true, 'default' => null),
    'indexes' => array(

    ),
    'tableParameters' => array('charset' => 'utf8', 'collate' => 'utf8_general_ci', 'engine' => 'InnoDB')
);

    public function initWageCosts(){
    $data = array(
            (int) 0 => array(
                'WageCost' => array(
                    'id' => '694a171a-8563-11e6-baed-00113241b9d5',
                    'type' => 'Mini',
                    'start' => '2015-05-01',
                    'multiplier' => '1.5070',
                    'modified' => '2017-03-27 12:35:09',
                    'created' => null
                )
            )
        );

    $this->insertData($data,'WageCost','type');
}

public function insertData($data,$model,$checkField){
    //Fetch all Data of this table an make CheckField as key for easy Check later
    $modelObj = ClassRegistry::init($model);
    $this->$model->find('all', ['recursive' => -1]);
    $keyArray = Set::combine($data, '{n}.'.$model.'.'.$checkField,'{n}');

    //Go through each to be inserted dataset
    foreach($data as $d){
        //if the to be checked field do not exist in Database, Insert it
        if(empty($keyArray[$d[$model][$checkField]])){
            $this->$model->create();
            $this->$model->save($d);
        }
    }
}

0 个答案:

没有答案
相关问题