Magento 开发过程中常用的使用技巧与方法

资料来自网络,大部分没有经过验证,仅供参考:

1.属性Attribute  

产品属性操作:  

$product = Mage::getModel('catalog/product')->getCollection()->getFirstItem();  

foreach($product->getAttributes() as $att) {  

$group_id = $att->getData('attribute_group_id');  

$group = Mage::getModel('eav/entity_attribute_group')->load($group_id);  

var_dump($group);  

}  

$attrSetName = 'my_custom_attribute';  

$attributeSetId = Mage::getModel('eav/entity_attribute_set') ->load($attrSetName, 'attribute_set_name') ->getAttributeSetId();  

1.1 得到Product的属性id,即catalog_product_entity表的entity_type_id字段  

$productAttributeSets = $this->getProductAttributeSets();  

1.2 前台页面获取商品属性  

$_product->getResource()->getAttribute('cost')->getFrontend()->getValue($_product);  

Magento的产品属性,在catalog.xml中已经写进去了。你可以在product view中找到  

<block type="catalog/product_view_attributes" name="product.attributes" as="additional" template="catalog/product/view/attributes.phtml">  

<action method="addToParentGroup"><group>detailed_info</group></action>  

</block>  

现在只要在产品详细页(view.phtml)中想要的位置插入  

<?php echo $this->getChildHtml('additional') ?>  

1.3获取产品属性集  

$sets = Mage::getResourceModel('eav/entity_attribute_set_collection') ->setEntityTypeFilter(Mage::getModel('catalog/product')->getResource()->getTypeId()) ->load() ->toOptionHash();  

1.4 加载某个attribute:  

$attributeCode=Mage::getModel('catalog/resource_eav_attribute')  

->load($attrbuteId)  

->getData("attribute_code");  

1.5 获取所有的产品属性的attribute:  

$attributes = Mage::getResourceModel ( 'catalog/product_attribute_collection' )  

->addFieldToFilter ( "frontend_input", "select" )  

->load ();  

1.6 获取某个product的所有attribute:  

注:如果是在 collection 中获取自定义的attribute,必须加 addAttributeToSelect(), 如下:  

$product=Mage::getModel('catalog/product')->getCollection()->addAttributeToSelect("dropdownlistone")  

1.7 获取某个种类的所有attribute:  

$entityTypeId = Mage::getSingleton('eav/config')  

->getEntityType('catalog_product')  

->getEntityTypeId();  

$items = Mage::getResourceSingleton('catalog/product_attribute_collection')  

->setEntityTypeFilter($entityTypeId)  

->getItems();  

1.8 获取某个attribute的所有option:  

$attributeObject=Mage::getModel('eav/config')->getAttribute('catalog_product')->load($attributeId);  

$options = $attributeObject->setStoreId(Mage::app()->getStore()->getId())->getSource()->getAllOptions(false);  

$table = $attributeObject->getBackend()->getTable();  

public function getAttributeOptionsByAttributeCode($entityType, $attributeCode){  

$entityType = Mage::getSingleton('eav/config')->getEntityType($entityType);  

$attributeObject = Mage::getModel('customer/attribute')->loadByCode($entityType, $attributeCode);  

return $attributeObject->setStoreId(Mage::app()->getStore()->getId())->getSource()->getAllOptions(false);  

}  

或者:  

$optionCollection = Mage::getResourceModel('eav/entity_attribute_option_collection')  

->setAttributeFilter($attr_model->getId())  

->setStoreFilter($storeId, false)  

->load();  

1.9 获取某个attribute的所有多语言label:  

$attributeLabelsArray= Mage::getResourceModel('eav/entity_attribute')  

->getStoreLabelsByAttributeId($attrbuteId);  

1.10 获取某个attribute_set的所有attribute:  

$attributes = Mage::getResourceModel('catalog/product_attribute_collection')  

->setAttributeSetFilter($attribute_set_id)  

->load();  

$attributeSetCollection = Mage::getResourceModel('eav/entity_attribute_set_collection')  

->load();  

1.11 获取attribute 对象 by attribute code  

$muarqspFrom = Mage::getSingleton('eav/config')->getAttribute('catalog_product', ' muarqsp_from');  

$attrCollection = Mage::getResourceModel('eav/entity_attribute_collection')  

->setCodeFilter($attributeCode)  

->load()  

1.12 通过attributeName得到 attributeSetId  

Mage::getResourceModel('eav/entity_attribute_set_collection')  

->addFieldToFilter('attribute_set_name',$attributSetName)  

->getFirstItem()->getId();  

1.13 通过 attributeSetId得到attributeSetName  

Mage::getModel('eav/entity_attribute_set')  

->load($id)->getData("attribute_set_name");  

2. 产品相关操作  

2.1 产品缩略图  

$_thumb = Mage::helper('catalog/image')->init($product, 'thumbnail')->resize(50, 50)->setWatermarkSize('30x10');  

2.2 product collection  

$collection = Mage::getResourceModel('catalog/product_collection')  

->addStoreFilter()  

->addAttributeToSelect("*")  

->addAttributeToFilter('entity_id', array('in' => $products))  

->setPageSize(10)  

->setCurPage(1);  

2.3 删除一个product的所有的images//Get products gallery attribute  

$attributes = $product->getTypeInstance()->getSetAttributes();  

if (isset($attributes['media_gallery'])) {  

$gallery = $attributes['media_gallery'];  

//Get the images  

$galleryData = $product->getMediaGallery();  

foreach($galleryData['images'] as $image){  

//If image exists  

if ($gallery->getBackend()->getImage($product, $image['file'])) {  

$gallery->getBackend()->removeImage($product, $image['file']);  

$filename = Mage::getBaseDir('media') . DS . 'catalog'. DS .'product' . $image['file'];  

debug('<span style="color: green;">&lt;&lt; unlinked previous image '.$image['file'].' from product '.$product->getSku().'</span>');  

if (file_exists($filename) && is_file($filename) && is_writeable($filename)){  

@unlink($filename);  

debug('<span style="color: green;">(and deleted file '.$filename.')</span>');  

}else  

debug('<span style="color: red;">(but couldn\'t delete file '.$filename.')</span>');  

}  

}  

}  

3. website  

获取对象的方法:get_class_methods($object)  

返回对象的类名:get_class($object)  

3.1得到store id  

$store_id=Mage::getModel('core/store')  

->getCollection()  

->addFieldToFilter ( "code", "france_fr" )  

->getFirstItem()->getData('store_id');  

or  

Mage::getModel('core/store')->load('france_fr')->getId()  

3.2 得到website config  

//$website can be string or id  

$import_type = Mage::getModel('core/website')->load($website)->getConfig('maps/stock_import/stock_limit');  

if( $import_type===false ){  

//get admin config  

$import_type=Mage::getStoreConfig('maps/stock_import/import_type'0);  

}  

获取后台的配置  

Mage::getStoreConfig("clientnumber/total_config/service_ip",0); //get admin config  

3.3 generate skin url  

Mage::getDesign()->getSkinUrl('images/our_shops/shop_logo_default.jpg');  

3.4 generate select html  

$html = $this->getLayout()->createBlock('core/html_select')  

->setName($name)  

->setId($id)  

->setTitle(Mage::helper('directory')->__($title))  

->setClass('validate-select')  

->setValue($defValue)  

->setOptions($options)  

->getHtml();  

3.5 获取这个网站所代表的国家的代号(如:FR)  

Mage::getModel('directory/country')  

->load(Mage::getStoreConfig('general/country/default'))->getIso2Code(),  

3.6 获取登录的用户信息  

Mage::getSingleton('customer/session')->getCustomer()  

3.7 session,cookie  

1) 获取session  

$session = Mage::getSingleton('customer/session');  

2) session,cookie设置  

(1) Model:  

Mage::getModel(‘core/cookie’); Mage::getModel(‘core/session’);  

(2)Set Method:  

Mage::getSingleton(‘core/cookie’)->set(‘name’,'value’); Mage::getSingleton(‘core/session’)->set(‘name’,'value’);  

(3)Get method:  

Mage::getSingleton(‘core/cookie’)->get(‘name’); Mage::getSingleton(‘core/session’)->get(‘name’);  

3.8 Request对象  

Mage::app()->getRequest()  

3.9 调用Model对象  

Mage::getModel('infinity/model');  

3.10 输出配置文件  

//header(‘Content-Type: text/xml’);  

header(‘Content-Type: text/plain’);  

echo $config = Mage::getConfig() ->loadModulesConfiguration(‘system.xml’) ->getNode() ->asXML();  

exit;  

3.11 得到Magento分类的URL  

Mage::getModel('catalog/category')->load(17)->getUrl();  

3.12 build your URL with valid keys  

Mage::helper("adminhtml")->getUrl("mymodule/adminhtml_mycontroller/myaction/",array("param1"=>1,"param2"=>2));  

3.13 create key values  

Mage::getSingleton('adminhtml/url')->getSecretKey("adminhtml_mycontroller","myaction");  

3.14 disable security feature in the admin panel 在管理面板中禁用安全功能  

admin panel -> System -> Configuration -> Admin section: “Add Secret key to Urls”.  

3.15 后台模块跳转:  

Mage::app()->getResponse()->setRedirect(Mage::helper('adminhtml')->getUrl("adminhtml/promo_quote/index"));  

3.16 get a drop down lists options for a mulit-select attribute 多属性选择下拉列表  

$attribute = Mage::getModel('eav/config')->getAttribute('catalog_product', 'attribute_id');  

foreach ( $attribute->getSource()->getAllOptions(true, true) as $option)  

{  

$attributeArray[$option['value']] = $option['label'];  

}  

3.17 获取栏目图片  

public function getImageUrl($category) {  

return Mage::getModel('catalog/category')->load($category->getId())->getImageUrl();  

}  

public function getThumbnailUrl($category) {  

$image=Mage::getModel('catalog/category')->load($category->getId())->getThumbnail();  

if ($image) {  

$url = Mage::getBaseUrl('media').'catalog/category/'.$image;  

}  

return $url;  

}  

3.18 判断是否首页:$this->getIsHomePage()  

Mage::getSingleton('cms/page')->getIdentifier() == 'home' && Mage::app()->getFrontController()->getRequest()->getRouteName() == 'cms' )  

3.19 主题颜色  

$attributes = $_product->getAttributes();  

$themeColor = $attributes['theme_color']->getFrontend()->getValue($_product);  

3.20 获取configurable产品simple product  

if($_product->getTypeId() == "configurable"):  

$ids = $_product->getTypeInstance()->getUsedProductIds();  

foreach ($ids as $id) :  

$simpleproduct = Mage::getModel('catalog/product')->load($id);  

$simpleproduct->getName()." - ".(int)Mage::getModel('cataloginventory/stock_item')->loadByProduct($simpleproduct)->getQty();  

$childProducts = Mage::getModel('catalog/product_type_configurable')->getUsedProducts(null, $product);  

endforeach;  

endif;  

3.21 get the attributes of Configurable Product.  

$attributes = $product->getTypeInstance(true)->getConfigurableAttributes($product);  

3.22 当前路径  

$currentUrl = $this->helper('core/url')->getCurrentUrl();  

3.23 通过资源配置方式创建目录  

$installer = $this; $installer->startSetup(); // make directory for font cache  

try {  

$domPdfFontCacheDir = join(DS, array('lib', 'Symmetrics', 'dompdf', 'fonts'));  

$domPdfFontCacheDir = Mage::getBaseDir('var') . DS . $domPdfFontCacheDir;  

if (!file_exists($domPdfFontCacheDir)) {  

mkdir($domPdfFontCacheDir, 0777, true);  

}  

} catch(Exception $e) {  

throw new Exception( 'Directory ' . $domPdfFontCacheDir . ' is not writable or couldn\'t be ' . 'created. Please do it manually.' . $e->getMessage() );  

}  

$installer->endSetup();  

3.24 在controllers 实现跳转  

Mage::app()->getFrontController() ->getResponse() ->setRedirect('http://your-url.com');  

×××××  

$cms_id = Mage::getSingleton('cms/page')->getIdentifier();  

$cms_title = Mage::getSingleton('cms/page')->getTitle();  

$cms_content = Mage::getSingleton('cms/page')->getContent();  

3.25 获取当前站点货币符号  

$storeId = (int) $this->getRequest()->getParam('store', 0);  

$store=Mage::app()->getStore($storeId);  

$currencyCode=$store->getBaseCurrency()->getCode();  

$attribute = Mage::getModel('catalog/resource_eav_attribute')->load($attributeId);  

$attributeData = $attribute->getData();  

$frontEndLabel = $attributeData['frontend_label'];  

$attributeOptions = $attribute->getSource()->getAllOptions();  

3.26 设置meta信息  

$template = Mage::getConfig()->getNode('global/page/layouts/'.Mage::getStoreConfig("featuredproducts/general/layout").'/template');  

this->loadLayout(); $this->getLayout()->getBlock('root')->setTemplate($template);  

$this->getLayout()->getBlock('head')->setTitle($this->__(Mage::getStoreConfig("featuredproducts/general/meta_title")));  

$this->getLayout()->getBlock('head')->setDescription($this->__(Mage::getStoreConfig("featuredproducts/general/meta_description")));  

$this->getLayout()->getBlock('head')->setKeywords($this->__(Mage::getStoreConfig("featuredproducts/general/meta_keywords")));  

$this->renderLayout();  

4.  

magento中调用static block(静态块)的几种方法  

通常情况下,在magento程序中使用静态块用来创建广告、促销图片及静态的内容等等  

以下以在magento中利用静态块来创建首页两侧的广告  

在后台创建一个ad1静态块  

(1)如果要在.phtml文件中直接调用这个静态块,那可以采用以下方法  

<?php  

$block = Mage::getModel(‘cms/block’)  

->setStoreId(Mage::app()->getStore()->getId()) ->load(‘ad1′);  

$content = $block->getContent(); // Block的原始内容已经获得  

$processor = Mage::getModel(‘core/email_template_filter’);  

echo $html = $processor->filter($content);  

?>  

Mage::getModel(‘core/email_template_filter’)->filter()是必须的,因为Static Block里可能包含Magento的模板语言(如:{{store url=”"}}),fiter将翻译成实际的值  

Magento中调用静态Block主要有两个地方。  

是否感觉这代码太长了呢,那你还可以这么写  

<?php echo $this->getLayout()->createBlock('cms/block')->setBlockId('order_form')->toHtml() ?>  

(2)在CMS页面的Content中调用这个静态块呢?你可以采用以下方法  

{{block type=”cms/block” name=”cms_ad1_block” block_id=”ad1″ }}  

(3)在layout中调用静态块  

<reference name=”footer”>  

<block type=”cms/block” name=”ad1″ before=”-”>  

<action method=”setBlockId”><block_id>ad1</block_id></action>  

</block>  

</reference>  

5. 时间  

5.1 获取当前的时间  

1) $date = Mage::app()->getLocale()->date(Mage::getSingleton('core/date')->gmtTimestamp(), null, null);  

$date = $date->toString('yyyy-MM-dd hh:m:s');  

2) Mage::getModel('core/date')->date(); date("Y-m-d", Mage::getModel('core/date')->timestamp(time()));  

Magento中默认时区为GMT, 不能直接使用time(), date()等方法,否则会出现时间差。  

用下面的方法取当前时间(和后台设置的时区一致):  

date("Y-m-d", Mage::getModel('core/date')->timestamp(time()));  

获得UTC时间的方法  

$date = Mage::app()->getLocale()->utcDate($store, $value, true, Varien_Date::DATETIME_INTERNAL_FORMAT);  

$this->setData(‘date_start’, $date->toString(Varien_Date::DATETIME_INTERNAL_FORMAT));  

$date = Mage::app()->getLocale()->date();  

$dStr = $date->toString(Varien_Date::DATETIME_INTERNAL_FORMAT);  

//$dStr 可以用于存储到数据库的datetime字段.  

5.2 格式化时间  

Mage::app()->getLocale()->date($creditMemo->getCreatedAt())->toString('YYYY-MM-dd');  

或:  

$this->_filterDates($data, array('date_expires'));  

protected function _filterDates($array, $dateFields)  

{  

if (empty($dateFields)) {  

return $array;  

}  

$filterInput = new Zend_Filter_LocalizedToNormalized(array(  

'date_format' => Mage::app()->getLocale()->getDateFormat(Mage_Core_Model_Locale::FORMAT_TYPE_SHORT)  

));  

$filterInternal = new Zend_Filter_NormalizedToLocalized(array(  

'date_format' => Varien_Date::DATE_INTERNAL_FORMAT  

));  

foreach ($dateFields as $dateField) {  

if (array_key_exists($dateField, $array) && !empty($dateField)) {  

$array[$dateField] = $filterInput->filter($array[$dateField]);  

$array[$dateField] = $filterInternal->filter($array[$dateField]);  

}  

}  

return $array;  

}  

5.3 加减日期  

Mage::app()->getLocale()->date()->sub("3",Zend_Date::DAY)->toString('YYYY-MM-dd HH:mm:ss');  

5.4 日期过滤  

$todayDate = Mage::app()->getLocale()->date()->toString(Varien_Date::DATETIME_INTERNAL_FORMAT);  

$this->_getProductCollection()  

->addAttributeToFilter('news_from_date', array('or'=> array(  

0 => array('date' => true, 'to' => $todayDate),  

1 => array('is' => new Zend_Db_Expr('null')))  

), 'left')  

->addAttributeToFilter('news_to_date', array('or'=> array(  

0 => array('date' => true, 'from' => $todayDate),  

1 => array('is' => new Zend_Db_Expr('null')))  

), 'left')  

->addAttributeToFilter(  

array(  

array('attribute' => 'news_from_date', 'is'=>new Zend_Db_Expr('not null')),  

array('attribute' => 'news_to_date', 'is'=>new Zend_Db_Expr('not null'))  

)  

)  

->addAttributeToFilter('visibility', array('in' => array(2, 4)))  

->addAttributeToSort('news_from_date', 'desc')  

->setPage(1, 4);  

5.5 判断日期是否有效  

Mage::app()->getLocale()->isStoreDateInInterval(Mage::app()->getStore(), $special_from_date, $special_to_date)  

6. collection  

6.1 在Configuation中添加validate  

<validate>validate-number</validate>  

6.2 获取当前的controller  

$moduleName=Mage::app()->getRequest()->getModuleName();  

$controllerName=Mage::app()->getRequest()->getControllerName();  

$actionName=Mage::app()->getRequest()->getActionName();  

$fullActionName=$moduleName."_".$controllerName."_".$actionName;  

6.3 controller 中 添加block  

$this->getLayout()  

->createBlock('clientnumber/inputform', 'checkout.cart.inputclientnumber')  

->setTemplate('clientnumber/input.phtml')  

->toHtml()  

6.5添加breadcrumbs在 controller中(为前端页面添加面包屑,如 Category/product这里的导航 ):  

在controller文件中填充面包屑数据,在block的phtml文件中显示  

1). 在controller的Action方法中  

//判断是否存在名字为breadcrumbs的Block(默认都存在,后面有说明)  

if ($breadcrumbsBlock = $this->getLayout()->getBlock('breadcrumbs')) {  

// 该条目有目标链接地址  

$breadcrumbsBlock->addCrumb('category', array(  

'label' => 'Category',  

'title' => 'Category Title',  

'link' => 'http://www.google.com',  

'readonly' => true,  

));  

// 该条目没有链接地址,一般作为最后一个条目  

$breadcrumbsBlock->addCrumb('product', array('label' => Mage::helper('catalog')->__('Product')));  

}  

2). 在该action对应的Layout文件中添加Block  

Xml代码:  

<block type="page/html_breadcrumbs" name="breadcrumbs" as="breadcrumbs"/>  

相应的在你的Block的合适位置输出面包屑  

<?php echo $this->getChildHtml('breadcrumbs'); ?>  

以上描述的是面包屑的一般原理,Magento实际上已经默认声明了Block  

Xml代码:  

<block type="page/html_breadcrumbs" name="breadcrumbs" as="breadcrumbs"/>  

而且默认的几个layout模板文件(page/1column.phtml,page/2columns-left.phtml..等)已经做了  

<?php echo $this->getChildHtml('breadcrumbs'); ?>  

6.6 filter in collection  

$collection = Mage::getModel('sales/order')->getCollection()  

->addFieldToFilter('status', array('eq'=>'pending'))  

->addFieldToFilter('created_at', array('datetime' => true, 'from'=>"2011-10-10 00:00:00",'to' => Mage::app()->getLocale()->date()->sub("3",Zend_Date::DAY)->toString('YYYY-MM-dd HH:mm:ss')));  

6.7 在controllers 实现跳转  

Mage::app()->getFrontController() ->getResponse() ->setRedirect('http://your-url.com');  

7. 获取quote中的所有的item  

$quote=Mage::getSingleton('checkout/session')->getQuote();  

foreach ($quote->getAllItems() as $item) {  

$proId[]=$item->getProduct()->getId();  

}  

8. 发送邮件  

$mailTransport = new Zend_Mail_Transport_Smtp( '192.168.0.1' );  

$mail = new Zend_Mail();  

$mail->setBodyText($content);  

$mail->setFrom("hello@example.com", 'Webmaster');  

$mail->addTo("bysoftgz@gmail.com", '');  

$mail->setSubject('Import attribute logs');  

$mail->send($mailTransport);  

9. block  

9.1 用block创建一个template  

<?php echo Mage::getBlockSingleton('inseecode/form')->getInseeFormHtml($this->getAddress(), 'customer');?>  

public function getInseeFormHtml($address, $type) {  

$this->setTemplate('inseecode/form.phtml');  

return $this->toHtml();  

}  

9.2 利用静态block  

<?php echo $this->getLayout()->createBlock('clientnumber/widget_name')  

->setObject($this->getAddress())  

->toHtml()  

?>  

9.3 调用static block  

1) 如果要在.phtml文件中直接调用这个静态块,那可以采用以下方法  

<?php $block = Mage::getModel('cms/block')  

->setStoreId(Mage::app()->getStore()->getId())  

->load('order_form');  

$content = $block->getContent(); // Block的原始内容已经获得  

$processor = Mage::getModel('core/email_template_filter');  

echo $html = $processor->filter($content);  

?>  
Mage::getModel(‘core/email_template_filter’)->filter()是必须的,  

因为Static Block里可能包含Magento的模板语言(如:{{store url=”"}}),fiter将翻译成实际的值  

Magento中调用静态Block主要有两个地方。  

是否感觉这代码太长了呢,那你还可以这么写  

<?php echo $this->getLayout()->createBlock(‘cms/block’)->setBlockId(‘order_form’)->toHtml() ?>  

2) magento中的CMS功能,可以让我们很方便的在PHP中嵌入经常要更改的内容,这样我们可以通过在CMS中直接修改文章内容,  

而不需要去修改源代码,最经典的就是我们的首页就是写在CMS Static block中的。  

如何在CMS页面的Content中调用这个静态块呢?你可以采用以下方法  

{{block type=”cms/block” name=”cms_test_block” block_id=”order_form” }}  

将里面order_form改成你的静态块对应的block_id则可  

3) 怎么样在layout中调用静态块呢?  

<reference name=”footer”>  

<block type=”cms/block” name=”order_form” before=”-”>  

<action method=”setBlockId”><block_id>order_form</block_id></action>  

</block>  

</reference>  

magento中调用CMS静态块(Static Block)教程到此就结束了,你应该能够灵活的运用magento中的静态块了吧!  

10. 获取指定level目录  

$parent = Mage::app()->getStore()->getRootCategoryId();  

$categoryModel = Mage::getModel('catalog/category');  

$storeCategories = $categoryModel->getCategories($parent, 2); //获取level 2  

11. 数据库  

11.1 修改数据库结构  

$installer->getConnection()->addColumn(  

$installer->getTable('enterprise_giftcardaccount/giftcardaccount'),  

'gift_card_type',  

"VARCHAR(200) DEFAULT ''");  

$installer->getConnection()->addColumn(  

$installer->getTable('enterprise_giftcardaccount/giftcardaccount'),  

'gift_card_type',  

"TINYINT( 1 ) UNSIGNED NOT NULL DEFAULT '0'");  

$installer->getConnection()->dropColumn($installer->getTable('eav_attribute'), 'use_in_super_product');  

$installer->run("ALTER TABLE `sales_flat_order` CHANGE `is_synced` `is_synced` INT( 4 ) NOT NULL ");  

11.2 magento操作数据库  

eg.1  

$this->getSelect()  

->from(array('e' => $this->getEntity()->getFlatTableName()), null)  

->columns(array('status' => new Zend_Db_Expr(Mage_Catalog_Model_Product_Status::STATUS_ENABLED)));  

$this->addAttributeToSelect(array('entity_id', 'type_id', 'attribute_set_id'));  

if ($this->getFlatHelper()->isAddChildData()) {  

$this->getSelect() ->where('e.is_child=?', 0);  

$this->addAttributeToSelect(array('child_id', 'is_child'));  

}  

$select=$this->getSelect()->from(array('e'=>$this->getEntity()->getEntityTable()));  

$select->joinRight( array('t'=>'test_product'), 'e.entity_id = t.entity_id', array() );  

eg.2  

$resource = Mage::getSingleton('core/resource');  

$read= $resource->getConnection('read');  

$tempTable = $resource->getTableName('eav_attribute'); //用其他表也是可以的  

$wheres = "`entity_type_id` =4 ";  

//SELECT count(*) as num FROM `eav_attribute` WHERE (`entity_type_id` =4 )  

//$select = $read->select() ->from($tempTable, array('count(*) as num')) ->where($wheres);  

//SELECT `eav_attribute`.* FROM `eav_attribute` WHERE (`entity_type_id` =4 )  

//$select = $read->select() ->from($tempTable) ->where($wheres);  

//SELECT `eav_attribute`.`attribute_code` FROM `eav_attribute` WHERE (`entity_type_id` =4 )  

$select = $read->select() ->from($tempTable, array('attribute_code')) ->where($wheres);  

$result = $read->fetchAll($select);  

eg.3  

$resource = Mage::getSingleton('core/resource');  

$read= $resource->getConnection('read');  

$select = "select * from catalog_product_entity where entity_id =5";  

$result = $read->fetchAll($select);  

//$result = $read->fetchOne($select);  

$instructors = array();  

foreach($result as $item){  

$instructors[$item['entity_id']] = array('position' => $item['sku']);  

}  

$dbw = Mage::getSingleton('core/resource')->getConnection('write');  

$sql="update catalog_product_entity set sku='sku11' where entity_id=5";  

$dbw->query( $sql );  

magento--调用数据库的步骤--使用magento机制访问数据库  

在后台附加一个属性,譬如品牌.然后,在产品详细页面,把同个品牌的产品都调用出来!下面是程序代码  

public function getOtherProduct(){  

$_producty = $this->getProduct();  

$_biaoshi = $_producty['biaoshi'];  

$resource = Mage::getSingleton('core/resource');  

$read = $resource->getConnection('catalog_read');  

$categoryProductTable = $resource->getTableName('catalog/category_product');  

//$productEntityIntTable = $resource->getTableName('catalog/product_entity_int'); // doesn't work  

$productEntityIntTable = (string)Mage::getConfig()->getTablePrefix().'catalog_product_entity_int';  

$eavAttributeTable = $resource->getTableName('eav/attribute');  

$product_attribute_valueTable = (string)Mage::getConfig()->getTablePrefix().'catalog_product_entity_varchar';  

//return $product_attribute_valueTable;  

// var_dump($productEntityIntTable); exit;  

// Query database for featured product  

$select = $read->select()  

->from(array('cp'=>$categoryProductTable))  

// ->join(array('pei'=>$productEntityIntTable),'pei.entity_id=cp.product_id', array())  

->join(array('pss'=>$product_attribute_valueTable),'pss.entity_id=cp.product_id',array())  

->joinNatural(array('ea'=>$eavAttributeTable))  

// ->joinNatural(array('pss'=>$product_attribute_valueTable))  

// ->where('cp.category_id=?', $categoryId)  

->where('pss.value=?',$_biaoshi)  

// ->where('ea.a')  

->where('ea.attribute_code="biaoshi"');  

$rows = $read->fetchAll($select);  

$ids = array();  

foreach($rows AS $row) {  

$ids[] = $row['product_id'];  

}  

$ret = implode(',', $ids);  

$ids = array_unique($ids);  

// return $ids;  

$productList = array();  

foreach($ids as $idq){  

$product = Mage::getModel('catalog/product')->load($idq);  

$productList[] = $product;  

}  

// $product = Mage::getModel('catalog/product')->load($this->getProductId());  

// $collection = Mage::getModel('catalog/product')->getCollection();  

// $collection->getSelect()->where('e.entity_id in (?)', $ids);  

// $collection->addAttributeToSelect('*');  

// $productList = $collection->load();  

return $productList;  

// return $ids;  

}  

如果你想成为一个magento二次开发程序员,上面的代码,你会感兴趣  

12. 打印php调试信息的代码  

$array = debug_backtrace();  

//print_r($array);//信息很齐全  

unset($array[0]);  

foreach($array as $row)  

{  

$html .= $row['file'].':'.$row['line'].'行,调用方法:'.$row['function']."<p>";  

}  

echo $html;  

exit();  

13. test code for quote  

$quote=Mage::getSingleton('checkout/session')->getQuote();  

foreach ($quote->getAllVisibleItems() as $item) {  

echo $item->getProductId();  

} 
一章:Magento介绍...................................................................................................................4 Magento 的特色......................................................................................................................5 什么是Magento........................................................................................................................6 Magento的元素和专业术语....................................................................................................6 网站和商店(website and store)...................................................................................7 网站(website)..............................................................................................................7 商店(store)..................................................................................................................7 商店界面(store views)................................................................................................7 Magento的程序架构................................................................................................................8 内核(Core)..................................................................................................................9 本地的(Local).............................................................................................................9 社区(Community).......................................................................................................9 扩展(Extensions).........................................................................................................9 模块(Modules)............................................................................................................9 界面(Interface)..........................................................................................................10 主题(Themes)............................................................................................................10 区块(Blocks).............................................................................................................11 第二章:Magento入门.................................................................................................................12 Magento的系统需求..............................................................................................................12 Magento下载..........................................................................................................................13 Magento安装和配置..............................................................................................................14 Magento后台控制面板介绍..................................................................................................14 创建多网站和商店(Creating Multiple Websites and Stores)...................................14 缓存管理(Cache Management).................................................................................16 第三章:建立目录........................................................................................................................17 产品目录概念总览................................................................................................................17 设置默认项....................................................................................................................17 产品图片存放目录(Product Image Placeholders)....................................................19 创建分类(Creating Categories).................................................................................21 分类添加产品(Assigning products at the category level)....................................24 定制分类页面的外观(Assigning designs at the category level)..............................25 在分类页面使用静态区块(Using static blocks with categories).........................26 属性(Attributes)................................................................................................................27 创建属性(Creating an Attribute)...............................................................................27 特性(Properties)........................................................................................................27 管理标记/选项(Manage Label/Options)...................................................................30 管理属性集(Managing Attribute Sets).....................................................................31 产品(Procucts)..................................................................................................................34
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值