Model data in schema create with custom connection

50 views Asked by At

I've an AppSchema where I insert some rows into MySQL. So far so good:

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

I've learnt that --connection switch is intentionally overridden by each Model::$useDbConfig:

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

Yet I'm unable to insert my rows in anything else than 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(/*...*/);
    }
}

What did I misunderstood?

1

There are 1 answers

0
ndm On BEST ANSWER

The Cookbook example is wrong, there is no such syntax, the second argument of ClassRegistry::init() is a boolean.

The first argument accepts an array to pass further options:

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

See also the slightly broken API docs API > ClassRegistry::init() :)