Magento学习手记(第九天)
第九天
一、 数据库实例测试:数据库连接
1. 创建Databasetest模块,配置相关模块config.xml文件及系统etc模块配置文件;
2. 在模块配置文件config.xml中增加前端路由配置,并创建前端动作控制器;
3. 在前端动作控制器类的方法中增加数据库测试代码;
1 $resource = Mage::getSingleton ( 'core/resource' ); 2 $connection = $resource->getConnection ( 'core_read' ); 3 $result = $connection->query ( 'select * from ym_core_store' )->fetchAll (); 4 Zend_Debug::dump ( $result ); 5 6 $dbConfig = array ( 7 'host' => 'localhost', 8 'dbname' => 'sku_record', 9 'username' => 'root', 10 'password' => '' 11 ); 12 13 $_resource = Mage::getSingleton ( 'core/resource' ); 14 $connection = $_resource->createConnection ( 'sku_record', 'pdo_mysql', $dbConfig ); 15 $results = $connection->query ( 'select * from ym_sku_record' )->fetchAll (); 16 Zend_Debug::dump ( $results );
注:这里我们使用单例模式singleton获取的数据模型对象。
二、 数据库实例测试:一般数据模型使用
方式一:SQL方式
1 $_resource = Mage::getSingleton ( 'core/resource' ); 2 $connection = $_resource->getConnection ( 'core_read' ); 3 $result=$connection->query('select * from 4 ym_catalog_product_entity')->fetchAll(); 5 Zend_Debug::dump ( $result );
方式二:ORM方式
1 $_products = Mage::getModel ( 'catalog/product' )->getCollection () 2 foreach ( $_products as $_product ) { 3 Zend_Debug::dump ( $_product->debug () ); 4 }
重要概念:
数据库表:数据库表用户存储实体对象具体数据,数据库表之间相关关联;
Model对象:Model对象是从数据库表中取出的一行所形成的返回实例的一个类,在该类中有许多业务逻辑或方法等;
Resource Model对象:Resource Model是连接模型与数据库表的一个类,例如save()方法;
Resource Collection对象:该对象是处理实体集合的一个类;