我使用 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/