如何让我的收藏使用其他数据库连接?
-
16-10-2019 - |
题
因此,我已经扩展了一个Magento系列,以获取自己的收藏,只想使用其他数据库连接。我试图做的是定义连接 config.xml 像这样:
<global>
<resources>
<externaldb_write>
<connection>
<use>externaldb_database</use>
</connection>
</externaldb_write>
<externaldb_read>
<connection>
<use>externaldb_database</use>
</connection>
</externaldb_read>
<externaldb_setup>
<connection>
<use>core_setup</use>
</connection>
</externaldb_setup>
<externaldb_database>
<connection>
<host><![CDATA[localhost]]></host>
<username><![CDATA[db_username]]></username>
<password><![CDATA[db_password]]></password>
<dbname><![CDATA[db_name]]></dbname>
<model>mysql4</model>
<type>pdo_mysql</type>
<active>1</active>
</connection>
</externaldb_database>
</resources>
</global>
然后在我的压倒式构造函数中,做:
class VMR_Customreports_Model_Resource_Storeoverview_Collection extends Mage_Reports_Model_Resource_Order_Collection
{
public function __construct()
{
parent::__construct();
$resource = Mage::getSingleton('core/resource');
$conn = $resource->getConnection('externaldb_read');
$this->setConnection($conn);
}
.....
}
这似乎没有任何效果。如果不起作用,我会期望发生错误。我该怎么办?
更新:经过更多调试后,我注意到下面的该代码返回原始DB连接,而不是我在XML中定义的连接。这是为什么?
$conn = $resource->getConnection('externaldb_read');
解决方案
快速检查(请参见下面的测试案例)实际上显示您在做什么应该只是桃子。
因此,我怀疑您的配置中有一些错误。请编辑您的帖子,至少将您的收藏班包括在内 __construct
和 _construct
方法。
另外,如果您不使用 sales/order
资源模型,也请将其包含在其构造函数方法中。
更新:
我只是注意到你正在使用 $resource->getConnection('reportingdb_read');
在您的构造函数中。
在配置xml中,连接称为 <externaldb_read>
.
笔记: reportingdb_read
!= externaldb_read
也许那只是您帖子中的复制和粘贴错误,但是如果没有,则必须使用
$resource->getConnection('externaldb_read');
如果不是问题,请再次更新您的帖子,我将帮助进一步挖掘。
// Test to confirm a connection set via setConnection() on a
// Mage_Reports_Model_Resource_Order_Collection instance is used
// to load the collection data.
class Reports_CollectionTest extends PHPUnit_Framework_TestCase
{
public static function setUpBeforeClass()
{
require_once 'app/Mage.php';
Mage::setIsDeveloperMode(true);
Mage::app('admin');
}
protected function getConnectionMock()
{
$mockSelect = $this->getMockBuilder('Varien_Db_Select')
->disableOriginalConstructor()
->getMock();
$mockConn = $this->getMockBuilder('Varien_Db_Adapter_Pdo_Mysql')
->disableOriginalConstructor()
->getMock();
$mockConn->expects($this->once())
->method('select')
->will($this->returnValue($mockSelect));
$mockConn->expects($this->once())
->method('fetchAll');
return $mockConn;
}
/**
* @test
*/
public function testCollectionConnection()
{
$mockCon = $this->getConnectionMock();
$collection = new Mage_Reports_Model_Resource_Order_Collection;
$collection->setConnection($mockCon);
$this->assertSame($mockCon, $collection->getConnection());
$collection->load();
}
}