使用自定义连接创建模式中的模型数据

Model data in schema create with custom connection

我有一个 AppSchema,我在其中插入一些行到 MySQL。到目前为止一切顺利:

$foo = ClassRegistry::init('Foo');
$foo->create();
$foo->saveMany(/*...*/);

我了解到 --connection 开关被每个 Model::$useDbConfig:

覆盖 intentionally

If you use models in your callbacks make sure to initialize them with the correct datasource, lest they fallback to their default datasources:

public function before($event = array()) {
    $articles = ClassRegistry::init('Articles', array(
        'ds' => $this->connection
    ));
    // Do things with articles.
}

但是我无法在除 default:

以外的任何地方插入我的行
Console/cake schema create --connection test --file schema_foo.php
class AppSchema extends CakeSchema {
    public function __construct($options = array()) {
        parent::__construct($options);
        // `$this->connection` contains value from `--connection`
        $foo = ClassRegistry::init('Foo', array('ds' => $this->connection));
        // `--connection` is ignored, `default` gets initialised
        $foo->create();
        $foo->saveMany(/*...*/);
    }
}

我误会了什么?

Cookbook的例子是错误的,没有这样的语法,ClassRegistry::init()的第二个参数是一个布尔值。

第一个参数接受一个数组以传递更多选项:

ClassRegistry::init(array(
    'class' => 'Foo'
    'ds' => $this->connection
));

另请参阅稍微损坏的 API 文档 API > ClassRegistry::init() :)