CakePHP-';控制台/蛋糕模式创建';始终将记录插入到';默认值';连接,而不遵循--connection参数
我使用Cake控制台生成了一个模式文件,该模式文件使用after()方法在数据库中创建一些默认记录 “schema create”命令对默认数据库运行良好,但当我尝试对测试数据库执行相同的命令并使用--connection参数时。。。奇怪的事情发生了。它确实在测试数据库下创建了表,但它试图在默认数据库上插入记录 我认为这可能与after()方法有关 这是我的模式文件:CakePHP-';控制台/蛋糕模式创建';始终将记录插入到';默认值';连接,而不遵循--connection参数,cakephp,console,schema,cakephp-2.x,Cakephp,Console,Schema,Cakephp 2.x,我使用Cake控制台生成了一个模式文件,该模式文件使用after()方法在数据库中创建一些默认记录 “schema create”命令对默认数据库运行良好,但当我尝试对测试数据库执行相同的命令并使用--connection参数时。。。奇怪的事情发生了。它确实在测试数据库下创建了表,但它试图在默认数据库上插入记录 我认为这可能与after()方法有关 这是我的模式文件: <?php // Use this Schema for all Stage_2.0 Releases App::us
<?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);
}
你有没有仔细检查过你的数据库配置文件中的一切都正常?我有完全相同的问题。你解决了这个问题吗?@lordg我向CakePHP报告了这个错误,他们说它是在CakePHP 2.4.5稳定版中解决的。确保您的CakePHP是最新的。。。如果没有,那么你可以在这里报告这个问题:NVM,看起来你已经击败了我:是啊,太棒了,谢谢!请注意,您仍然需要CakePHP/2.4.5或更高版本才能使用正确的值填充$this->connection
。
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);
}