现在的位置: 首页 > 综合 > 正文

Magento – 模型类如何获得资源模型得实例

2018年05月27日 ⁄ 综合 ⁄ 共 1283字 ⁄ 字号 评论关闭

1. etc/config.xml有如下配置

<global>
<models>
<hotel>
<class>Cartz_Hotel_Model</class>
<resourceModel>hotel_mysql4</resourceModel>
</hotel>
<hotel_mysql4>
<class>Cartz_Hotel_Model_Mysql4</class>
<entities>
<room>
<table>rooms</table>
</room>
</entities>
</hotel_mysql4>
</models>
<resources>
<hotel_setup>
<setup>
<module>Cartz_Hotel</module>
</setup>
<connection>
<use>core_setup</use>
</connection>
</hotel_setup>
<hotel_write>
<connection>
<use>core_write</use>
</connection>
</hotel_write>
<hotel_read>
<connection>
<use>core_read</use>
</connection>
</hotel_read>
</resources>
</global>

2. 模型
类为model/Room.php

<?php
class Cartz_Hotel_Model_Room extends Mage_Core_Model_Abstract{
protected function _construct() {
$this->_init('hotel/room');
}
public function listing(){
$this->_getResource()->findAll();
}
}
?>
3. 相应的资源
模型
类是model/Mysql4
<?php
class Cartz_Hotel_Model_Mysql4_Room extends Mage_Core_Model_Mysql4_Abstract{
protected function _construct(){
   $this->_init('hotel/room', 'id');
}
public function findAll() {
   $handle = $this->_getWriteAdapter();
   $query = $handle->query('select name from rooms');
   while ($row = $query->fetch()) {
$row = new Varien_Object($row);
      echo $row->getName() . "<br/>";
}
}
}
?>
这段代码昭示了两个知识点:

1. model类的方法_getResource()获得相应资源
模型
类的实例

2. 在资源
模型
类中, 方法 _getWriteAdapter()用来获得数据库的连接句柄

本文转自:http://hi.baidu.com/pw425/blog/item/9a2a6a1d401ecd8286d6b64d.html

抱歉!评论已关闭.