---
title: "magento -- 在magento下如何直接操作数据库"
author: "mypages"
date: "2009-09-21T19:16:25Z"
tags: ["SQL"]
slug: "magento-magento"
draft: false
lastmod: "2009-09-21T19:16:25Z"
id: 473523
url: "https://mypages.iteye.com/blog/473523"
---

magento -- 在magento下如何直接操作数据库

在magento中,要操作数据库,首先你需要一个resource model(翻译成"资源模型",magento中把数据库模型类称为一种资源(当然是相对程序来说的)),然后通过这个resource获取一个对数据库的连接.这样你就得到了一个Varien PDO Adapter对象,通过这个对象就可以直接通过sql语句操作.

view plaincopy to clipboardprint?  
$w = Mage::getSingleton(’core/resource’)-&gt;getConnection(’core\_write’);    
$result = $w-&gt;query(’select ’entity\_id’ from ’catalog\_product\_entity’);    
if (!$result) {    
return false;    
}    
$row = $result-&gt;fetch(PDO::FETCH\_ASSOC);    
if (!$row) {    
return false;    
}   
$w = Mage::getSingleton(’core/resource’)-&gt;getConnection(’core\_write’);  
$result = $w-&gt;query(’select ’entity\_id’ from ’catalog\_product\_entity’);  
if (!$result) {  
return false;  
}  
$row = $result-&gt;fetch(PDO::FETCH\_ASSOC);  
if (!$row) {  
return false;  
}

 

 

 

 

想通过订单ID，来查询‘支付方式’和‘订单总价’:

这个功能MAGENTO已经有这样的接口了，你可以直接调用而不必采取这种方式。

$order ＝ Mage::getModel('sales/order')-&gt;load('order\_id');//取出订单号为order\_id的订单  
$order-&gt;getPayment()；  
...

//获取此订单的支付方式,同样的订单总价也有相应的方法来获取[](http://blog.csdn.net/xinhaozheng/archive/2009/03/30/4035124.aspx)