Magento 记事本

2019独角兽企业重金招聘Python工程师标准>>> hot3.png

Useful Website:

Magento api(API接口): http://devdocs.magento.com/guides/m1x/api/soap/catalog/catalog.html

Magento module creator(快速创建): http://www.silksoftware.com/magento-module-creator/

 

Common use function:

1\ 获取所有配置产品

$count = 5;

$offset = 0;

$category = Mage::getModel('catalog/category')->load($categoryId);

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

               ->addAttributeToSelect('*')

               ->addCategoryFilter($category) //获取指定类目的产品

               ->addAttributeToFilter('type_id', Mage_Catalog_Model_Product_Type::TYPE_CONFIGURABLE) //config product

               ->addAttributeToFilter('status',1) //enable product

               ->setOrder("updated_at","DESC"); //order by updataed_at desc

$collection->getSelect()->limit($count,$offset); //limit, from $offset, get $count products

foreach($collection as $product){

               echo $product->getId() . PHP_EOL;

}

 

2\ 获取配置产品的所有单品

if($_product = Mage::getModel('catalog/product')->loadByAttribute('sku','44025040956')){

               if($_product->isConfigurable()){

                              $allProducts = $_product->getTypeInstance(true)->getUsedProducts(null, $_product);

                              foreach($allProducts as $simpleProduct){

                                            echo $simpleProduct->getId() . PHP_EOL;

                              }

               }

               echo $_product->getId() . PHP_EOL;

}

 

3\ 获取指定产品信息

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

$product = Mage::getModel('catalog/product')->loadByAttribute('sku',$sku);

 

4\ 随机获取信息,关键:order(new Zend_Db_Expr('RAND()'))

$limit = 5;//获取5条信息

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

$collection->getSelect()->limit(5)->order(new Zend_Db_Expr('RAND()'));

 

5\ 快速操作数据库

注:在model/resource里

$conn = Mage::getSingleton("core/resource")->getConnection('core_read');

已经定义好了,$conn == $this->_getReadAdapter(). 同样也有$this->_getWriteAdapter()

如:Mage::getModel('newaddproducts/newaddproducts')->getResource()->getList()

第一种:

$conn = Mage::getSingleton("core/resource")->getConnection('core_read');

$sql = “select * from AA”;

$conn->fetchAll($sql);  //查询多条记录

$conn->fetchRow($sql);//查询一条记录

$conn->query($sql);   //执行sql语句(添加/修改/删除)

第二种:

如表log_product_sync,有字段taobaoid,status,info,其中taobaoid为主键,则:

$arrData = array(

               'taobaoid' => $id,

               'status'   => '11',

               'info'     => ‘test’

);

$conn = Mage::getSingleton("core/resource")->getConnection('log_read');

添加:$conn->insert('log_product_sync', $arrData);//成功返回1

修改:$conn->update('log_product_sync',$arrData,array('status = ?' => '11'));

执行:$conn->query($sql);

查询一条记录:

               $bind = array('type'=>$type,'taobaoid'=>$tbId);                                               

$select = $conn->select()->from('taobao_newadd')->where('type = :type and taobaoid = :taobaoid')->order('timestamp desc');  

$data = $conn->fetchRow($select,$bind);

第三种:

//添加

$model = Mage::getModel("imgprocess/imgprocess")

                              ->setData($data)

                              ->save();

//修改

$model = Mage::getModel("imgprocess/imgprocess")

                              ->addData($data)

                              ->setId($id) //$id 为主键

                              ->save();

//查询

$info = Mage::getModel("imgprocess/imgprocess")->load($id);

//删除

Mage::getModel("imgprocess/imgprocess")->load($id)->delete();

 

6\ 添加属性集

$skeletonId = 4;

$setId=Mage::getModel("catalog/product_attribute_set_api")->create($setName, $skeletonId);

 

7\ 添加属性

$data = array(

               "attribute_code" => 'customs_attribute_name',

               "frontend_input" => "select",

               "scope" => "global",

               "is_unique" => 0,

               "is_required" => 0,

               "apply_to" => array("simple", "grouped", "configurable"),

               "is_configurable" => 1,

               "is_filterable"=>2,

               "is_searchable" => 1,

               "is_visible_in_advanced_search" => 0,

               "is_comparable" => 0,

               "is_used_for_promo_rules" => 1,

               "is_visible_on_front" => 0,

               "used_in_product_listing" => 0,

               "additional_fields" => array(),

               "frontend_label" => array(array("store_id" => "0", "label" => 'attribute_name'))

);

$attribute_id = Mage::getModel("catalog/product_attribute_api")->create($data);

 

8\ 为属性集添加属性

$result = Mage::getModel("catalog/product_attribute_set_api")->attributeAdd($attribute_id, $attribute_set_id);

 

9\ 为属性添加属性值

$data = array(

               "label" => array(

                              array("store_id" => array("0"), "value" => $option_name)

               ),

               "order" => "",

               "is_default" => "0"

);

Mage::getModel("catalog/product_attribute_api")->addOption($attribute_id, $data);

 

10\ 获取属性的所有属性值

$options = Mage::getModel("catalog/product_attribute_api")->options($attribute_id);

 

11\ 获取属性集的所有属性

$attributes = Mage::getModel('catalog/product')->getResource()

               ->loadAllAttributes()

               ->getSortedAttributes($set_id);

 

12\ 获取指定属性信息

$data = Mage::getModel('catalog/resource_eav_attribute')->load($attribute_id)->getData();

 

 

13\ 生成订单的Shipment and Add Tracking Number

$order = Mage::getModel("sales/order")->load(219);//orderId:219, order incrementId:100000219

$itemQty =  $order->getItemsCollection()->count();

$shipment = Mage::getModel('sales/service_order', $order)->prepareShipment($itemQty);

$shipment = new Mage_Sales_Model_Order_Shipment_Api();

$shipmentId = $shipment->create($order->getData('increment_id'));

var_dump($shipmentId);

if ($shipmentId){// $shipmentId is like 100000008,real shipment_id maybe is 8

               $CarrierCode = 'custom';

               $TrackingTitle = "title";

               $TrackingNumber= "num001";

               $TrackId=Mage::getModel('sales/order_shipment_api')->addTrack($shipmentId, $CarrierCode, $TrackingTitle, $TrackingNumber);

}

var_dump($TrackId);

 

//get shipment by shipment_id

$shipmentId = 7;

$shipment = Mage::getModel('sales/order_shipment')->load($shipmentId);

//get shipment by shipment increment_id

$shipmentIncId = '100000007';

$shipment = Mage::getModel('sales/order_shipment')->loadByIncrementId($shipmentIncId);

var_dump($shipment->getData());

 

14\ addFieldToFilter

$item = Mage::getModel('bucket/package_item')->getCollection()

                                            //->addAttributeToSelect('*')

                                            ->addFieldToFilter('order_item_id','963')->getFirstItem();

var_dump($item->getData());

 

15\ 打印合并后的System.xml文件,方便查找信息

require_once 'app/Mage.php';

Mage::setIsDeveloperMode(true);

Mage::app('admin');

ini_set('display_errors', 1);

umask(0);

header('Content-Type: text/xml');

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

 

16\ 获取用户的配置数据,即读取System.xml里配置的数据

echo Mage::getStoreConfig('trans_email/ident_sales/email');

 

17\ 获取但前货币和货币符号

$currencyCode = Mage::app()->getStore()->getCurrentCurrencyCode();

$symbol = Mage::app()->getLocale()->currency($currencyCode)->getSymbol();

//转换货币

$baseCurrencyCode = Mage::app()->getStore()->getBaseCurrencyCode(); 
$currentCurrencyCode = Mage::app()->getStore()->getCurrentCurrencyCode();

Mage::helper('directory')->currencyConvert($price(),$baseCurrencyCode,$currentCurrencyCode);

 

18\ 添加类目属性

1、 文本类型

$installer = new Mage_Eav_Model_Entity_Setup('core_setup');

$installer->startSetup();

$attribute = array(

    'type' => 'varchar',

    'label'=> 'My Text',

    'input' => 'text',

    'global' => Mage_Catalog_Model_Resource_Eav_Attribute::SCOPE_GLOBAL,

    'visible' => true,

    'required' => false,

    'user_defined' => true,

    'default' => "",

    'group' => "General Information"

);

$installer->addAttribute('catalog_category', 'my_text', $attribute);

$installer->endSetup();

2、 图片类型

$installer = new Mage_Eav_Model_Entity_Setup('core_setup');

$installer->startSetup();

$attribute = array(

    'type' => 'varchar',

    'label'=> 'Mobile Image',

    'input'=> 'image',

    'backend'=> 'catalog/category_attribute_backend_image',

    'required'=> false,

    'sort_order'=> 5,

    'global'=> Mage_Catalog_Model_Resource_Eav_Attribute::SCOPE_STORE,

    'group'=> 'General Information'

);

$installer->addAttribute('catalog_category', 'mobile_image', $attribute);

$installer->endSetup();

 

19\ 判断一个配置产品是否Out Of Stock

$product = Mage::getModel('catalog/product')->load('123');
if($product->isConfigurable()){
//config product
    $allProducts = $product->getTypeInstance(true)->getUsedProducts(null, $product);
    $singleStock = 0;
    foreach($allProducts as $simpleProduct){
        if(empty($simpleProduct->getIsInStock())){
            $singleStock++;
        }
    }
    if(count($allProducts) == $singleStock){
        
echo 'out stock';
    }
}else{
//single product
    if(empty($product->getIsInStock())){
        
echo 'out stock';
    }
}

 

20\ 获取 url 的 rewrite url

1\ use model

$url = "zymen-men-s-stretch-custom-fit-business-casual-suit-pants-235909.html";

$rewriteInfo = Mage::getModel('core/url_rewrite')->setStoreId(1)->loadByRequestPath($url);
var_dump($productRewrite->getData());

//array(10) { ["url_rewrite_id"]=> string(7) "1079437" ["store_id"]=> string(1) "1" ["id_path"]=> string(19) "80656800_1503557722" ["request_path"]=> string(69) "zymen-men-s-stretch-custom-fit-business-casual-suit-pants-235909.html" ["target_path"]=> string(69) "zymen-men-s-stretch-custom-fit-business-casual-suit-pants-235910.html" ["is_system"]=> string(1) "0" ["options"]=> string(2) "RP" ["description"]=> NULL ["category_id"]=> NULL ["product_id"]=> string(6) "235909" }

2\ use conn and get it's final url

$conn = Mage::getSingleton("core/resource")->getConnection('core_read'); 
function getTargetPath($conn,$requestPath){
    if(empty($requestPath)){
        return false;
    }
  if($row = $conn->fetchRow("select request_path,target_path,is_system from core_url_rewrite where request_path = '".$requestPath."' and store_id=1")){
        if(empty($row['is_system'])){
            echo '1-';
            return getTargetPath($conn,$row['target_path']);
        }else{
            echo '2-';
            return $row['request_path'];
        }
    }
}

$url = "zymen-men-s-stretch-custom-fit-business-casual-suit-pants-235909.html";
$rewriteUrl = getTargetPath($conn,$url);
var_dump($rewriteUrl);

//1-2-string(69) "zymen-men-s-stretch-custom-fit-business-casual-suit-pants-235910.html"

 

21\ Magento Grid 多表查询时字段冲突问题

错误提示大概是这样的

Integrity constraint violation: 1052 Column 'increment_id' in where clause is ambiguous

使用 代码  'filter_index'=>'main_table.increment_id', 可以解决这个问题

解决方法例子代码如下:
 $this->addColumn('real_order_id', array(
            'header'=> Mage::helper('sales')->__('Order #'),
            'width' => '80px',
            'type'  => 'text',
            'index' => 'increment_id',
            'filter_index'=>'main_table.increment_id',//use which table column
        ));

 

22\ getUrl

后台:

getUrl("*/*/getproductlist");?>

前台:

getUrl('*/*/updateProduct'); ?>

 

23\ get / set product category

get

$productId = 478509;

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

var_dump($product->getCategoryIds());

//array(5) { [0]=> string(1) "1" [1]=> string(1) "2" [2]=> string(2) "27" [3]=> string(2) "28"}

set

$productId = 478509;

$catalogId = 28;

if($catalogPath = Mage::getModel('catalog/category')->load($catalogId)->getPath()){
    $catalogIds = explode('/',$catalogPath);//$catalogPath = '1/2/27/28'
    if(!empty($catalogIds)){
        $product = Mage::getModel('catalog/product')->load($productId);
        $product->setCategoryIds($catalogIds);
        $product->save();
        return true;
    }
}

24\ 获取店铺本地语言

Mage::getStoreConfig('general/locale/code', $storeId)

like: en_US , es_ES ...

转载于:https://my.oschina.net/ganfanghua/blog/882792

你可能感兴趣的:(Magento 记事本)