2

Cake コンソールを使用してスキーマ ファイルを生成しました。スキーマ ファイルは after() メソッドを使用して、データベースにいくつかのデフォルト レコードを作成します。

'schema create' コマンドはデフォルト データベースでは問題なく動作しますが、テスト データベースに対して同じコマンドを実行しようとして --connection パラメータを使用すると、何か奇妙なことが起こりました。test データベースの下にテーブルを作成しましたが、デフォルト データベースにレコードを挿入しようとしました。

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 ...

}
4

1 に答える 1

3

OK、Mark Story の他の場所での応答の後、これに対する答えは、ロード後にモデルのデータベース構成を設定する必要があるということです。そうしないと、デフォルトも使用されます。

スキーマ クラスは db と直接統合されますが、モデルは通常の 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);
}
于 2014-02-03T08:14:41.930 に答える