CakePHP - 'Console/cake schema create' 始终将记录插入到 'default' 连接并且不遵守 --connection 参数

标签 cakephp console schema cakephp-2.x

我使用 Cake 控制台生成了一个架构文件,该架构文件使用 after() 方法在数据库中创建一些默认记录。

“schema create”命令对于默认数据库运行良好,但是当我尝试对测试数据库执行相同的命令并使用 --connection 参数时......发生了一些奇怪的事情。它确实在测试数据库下创建了表,但它尝试在默认数据库上插入记录。

我认为这可能与 after() 方法有关。

// Works. Creates the tables and inserts records successfully to the default

Console/cake schema create -s 1

// Breaks. Creates the tables under test but attempts to insert record in the default database

Console/cake schema create -s 1 --connection test

这是我的架构文件:

<?php 

// Use this Schema for all Stage_2.0 Releases
App::uses("ClassRegistry", "Utility");
App::uses("Shoe", 'Model');

class AppSchema extends CakeSchema {

    public function before($event = array()) {
            // the line below always outputs 'default'... even though --connection parameter is set to 'test'
        debug($this->connection);
        $db = ConnectionManager::getDataSource($this->connection);
        $db->cacheSources = false;
        return true;
    }

    public function after($event = array()) {
        if(isset($event['create'])){
            switch($event['create']){
                case "shoes":
                    $this->InsertSampleShoes();
                    break;
            }
        }
    }

    public function InsertSampleShoes(){
        $shoe = ClassRegistry::init("Shoe");
        $records = array(
            array(
                "Shoe" => array(
                    "name" => "Shoe 1"
                )
            ),
            array(
                "Shoe" => array(
                    "name" => "Shoe 2"
                )
            )
        );
        $shoe->saveAll($records);
    }

        // ... table name, column definitions etc ...

}

最佳答案

好吧,经过 Mark Story 在其他地方的回应,答案是你需要在加载模型后设置模型的数据库配置,否则它也会使用默认值。

模式类直接与数据库集成,而模型则通过正常的 cakephp 配置设置运行。

因此,对于上面的示例,请执行以下操作:

public function InsertSampleShoes(){
    $shoe = ClassRegistry::init("Shoe");
    $shoe->useDbConfig = $this->connection;
    $records = array(
        array(
            "Shoe" => array(
                "name" => "Shoe 1"
            )
        ),
        array(
            "Shoe" => array(
                "name" => "Shoe 2"
            )
        )
    );
    $shoe->saveAll($records);
}

关于CakePHP - 'Console/cake schema create' 始终将记录插入到 'default' 连接并且不遵守 --connection 参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18216235/

相关文章:

cakephp - 在 CakePHP 中定义模型类的层次结构

html - 最佳实践翻译 CakePHP 3.x __ 函数

php - 如何在 Symfony 4 控制台命令中获取应用程序根路径

java - 使用多个数据库目录对 Hibernate 进行单元测试

javascript - Business Catalyst - 如何从架构元内容中删除井号

javascript - CakePHP - 在 ajax 调用中处理 url

cakephp - cakephp 中的两个提交按钮将内容保存在两个不同的表中

javascript对象文字,值/无值?

c++ - 在 qt widgets 应用程序中显示 cmd 终端

sql - Oracle 是否允许跨模态视图?