从管理部分下订单后,我有一个事件观察者创建一个日志。如何将其插入数据库而不是日志文件?谁能提供一个好的教程。
1 回答
首先,您需要将 setup/read/write 部分添加到您的 config.xml。假设您的模块是测试/演示,那么您的设置部分可能看起来像这样:
<models>
<demo>
<class>Test_demo_Model</class>
<resourceModel>Demo_mysql4</resourceModel>
</demo>
<demo_mysql4>
<class>Test_Demo_Model_Mysql4</class>
<entities>
<demo>
<table>test_demo</table>
</demo>
</entities>
</demo_mysql4>
</models>
<resources>
<demo_setup>
<setup>
<module>Test_demo</module>
<class>Test_Demo_Model_Resource_Mysql4_Setup</class>
</setup>
<connection>
<use>core_setup</use>
</connection>
</demo_setup>
<demo_write>
<connection>
<use>core_write</use>
</connection>
</demo_write>
<demo_read>
<connection>
<use>core_read</use>
</connection>
</demo_read>
</resources>
此时我们需要创建初始化模型以便 magento 加载它。'demo/ _ ' 可以是 'demo/whateveryouwant' 只要你在整个模块中保持whateveryouwant 相同。'id' 是 magento 用于此模型的主键和标识符。
//Test/Demo/Model/Mysql4/Comment.php
class Test_Demo_Model_Mysql4_Comment extends Mage_Core_Model_Mysql4_Abstract
{
protected function _construct()
{
$this->init('demo/________', 'id');
{
}
从这里您将需要创建数据库安装脚本。这可以通过简单地创建文件 Test/Demo/sql/demo_setup/mysql4-install-0.1.0.php 来完成,其中 0.1.0 是配置文件中使用的版本号。它看起来像这样:
$installer = $this;
$installer->startSetup()
$installer->run("
#your create table goes here
");
$installer->endSetup();
这将做的是创建你的表,你可以使用
CREATE TABLE {$installer ->getTable('demo/_____') as defined in your configuration file to create the table name used in the file. This will also create an entry in the table core_resource that will specify the name and version number. In order to make a modification to the table you'll need to delete the original table as well as it's entry in core_resource. At this point you'll want to create a model to manage the data. Here's an example of that for a table that looks like:
//comment -String
//poster -String
//Id -int autoincrement
public function addComment($comment, $poster)
{
$comment = Mage::getModel('Demo/______');
$comment->setComment($comment);
$comment->setPoster($poster);
$comment->save();
}
对于诸如 poster_id 之类的列名,您将使用 setPosterId。使用驼峰式,每个大写字母在手前表示一个下划线。
海报_ID -> 海报ID 海报ID -> 海报ID
从数据库中获取值:
//using the same database example as above
public function getAllByPoster($poster)
{
$collection = Mage::getModel('Demo/________')->getCollection();
$collection->addFilter('poster', $poster);
return collection;
}
这将返回特定海报的所有帖子。但是有一个问题,尚未为此类定义获取集合。在我们可以看到如何从 getAllByPoster 显示这些结果之前,我们要创建最后一个文件。
//Test/Demo/Model/Mysql4/Comment/Collection.php
class Test_Demo_Model_Mysql4_Comment_Collection extends Mage_Core_Model_Mysql4_Collection_Abstract
{
protected function _construct()
{
$this->_init('comments/comment');
}
}
至此,我们拥有了使用 magento 的类读取和写入数据库所需的一切。要打印一个集合,我们只需:
foreach (Mage::getModel('demo/_____')->getAllByPoster($id) as $something)
并显示我们希望从中获得的各个属性。