Sie sind auf Seite 1von 17

addAttributeToFilter Conditionals In Magento

addAttributeToFilter is a function that can be called on a product collection in Magento. In short, it adds a condition to the WHERE part of the MySQL query used to extract a product collection from the database.

$_products = Mage::getModel('catalog/product')->getCollection() ->addAttributeToSelect(array('name', 'product_url', 'small_image')) ->addAttributeToFilter('sku', array('like' => 'UX%')) ->load(); The above code would get a product collection, with each product having it's name, url, price and small image loaded in it's data array. The product collection would be filtered and contain only products that have an SKU starting with UX. addAttributeToFilter Conditionals Notice above, I used the LIKE operator? There are many more operators in SQL and addAttributeToFilter will accept them all. I include them below as well as a reference for you. Hopefully this will save you some time. Equals: eq $_products->addAttributeToFilter('status', array('eq' => 1)); Not Equals - neq

$_products->addAttributeToFilter('sku', array('neq' => 'test-product')); Like - like $_products->addAttributeToFilter('sku', array('like' => 'UX%')); One thing to note about like is that you can include SQL wildcard characters such as the percent sign. Not Like - nlike $_products->addAttributeToFilter('sku', array('nlike' => 'err-prod%')); In - in

$_products->addAttributeToFilter('id', array('in' => array(1,4,74,98))); When using in, the value parameter accepts an array of values. Not In - nin $_products->addAttributeToFilter('id', array('nin' => array(1,4,74,98))); NULL - null $_products->addAttributeToFilter('description', 'null'); Not NULL - notnull $_products->addAttributeToFilter('description', 'notnull'); Greater Than - gt

$_products->addAttributeToFilter('id', array('gt' => 5)); Less Than - lt $_products->addAttributeToFilter('id', array('lt' => 5)); Greater Than or Equals To- gteq $_products->addAttributeToFilter('id', array('gteq' => 5)); Less Than or Equals To - lteq $_products->addAttributeToFilter('id', array('lteq' => 5)); addFieldToFilter() As far as I'm aware, addAttributeToFilter only works with products in Magento. When I first found out this fact I was not only shocked, I was worried! I thought that without it, I would have to custom craft all of my SQL queries. After scouring the Magento core code one night, I found addFieldToFilter(). This functions works in the exact same way and takes the same paramters, however it works on ALL collections and not just on products! Debugging The SQL Query There are two ways to debug the query being executed when loading a collection in Magento.

// Method 1 Mage::getModel('catalog/product')->getCollection()->load(true); // Method 2 (Quicker, Recommended) $collection = Mage::getModel('catalog/product')->getCollection(); echo $collection->getSelect(); Both method 1 and method 2 will print out the query but both will do it in slightly different ways. Method 1 prints the query out as well as loading the products while method 2 will just convert the query object to a string (ie. will print out the SQL). The second method is definitely better as it will be executed much quicker but I include them both here for reference.

Here, I am going to explain some database interaction functions present in the class Mage_Eav_Model_Entity_Collection_Abstract. These collection functions are very useful to select data from Magento database. We need them almost all the time for filtering collection object.

Below are some of the useful functions that we use most often. Class: Mage_Eav_Model_Entity_Collection_Abstract addAttributeToFilter: adds WHERE clause on $attribute specified by $condition /** * Add attribute filter to collection * * If $attribute is an array will add OR condition with following format: * array(

* array(attribute=>firstname, like=>test%), * array(attribute=>lastname, like=>test%), *) * * @see self::_getConditionSql for $condition * @param Mage_Eav_Model_Entity_Attribute_Interface|integer|string|array $attribute * @param null|string|array $condition * @param string $operator * @return Mage_Eav_Model_Entity_Collection_Abstract */ addAttributeToFilter($attribute, $condition=null, $joinType=inner) addAttributeToSelect: gets the value for $attribute in the SELECT clause; specify * to get all attributes (i.e. to execute SELECT *) /** * Add attribute to entities in collection * * If $attribute==* select all attributes * * @param array|string|integer|Mage_Core_Model_Config_Element $attribute * @param false|string $joinType flag for joining attribute * @return Mage_Eav_Model_Entity_Collection_Abstract */ addAttributeToSelect($attribute, $joinType=false) If an array is passed but no attribute code specified, it will be interpreted as a group of OR conditions that will be processed in the same way. If no attribute code is specified, it defaults to eq. $collection = Mage::getModel('catalog/product')->getCollection(); // select all attributes $collection->addAttributeToSelect('*'); // select specific attributes $collection->addAttributeToSelect(array('name', 'url_key', 'type_id')); // select only those items whose status = 1 $collection->addAttributeToFilter('status', 1); // alternative to select only those items whose status = 1 $collection->addAttributeToFilter('status', array('eq' => 1)); // using LIKE statement $collection->addAttributeToFilter('sku', array('like' => '%CH%')); // using IN statement, // i.e. selecting only those items whose ID fall in the given array $collection->addAttributeToFilter('id', array('in' => array(1, 14, 51, 52))); // selecting only those items whose ID is greater than the given value

$collection->addAttributeToFilter('id', array('gt' => 5)); // select by date range $collection->addAttributeToFilter('date_field', array( 'from' => '10 September 2010', 'from' => '21 September 2010', 'date' => true, // specifies conversion of comparison values )); // Add OR condition: $collection->addAttributeToFilter(array( array( 'attribute' => 'field_name', 'in' => array(1, 2, 3), ), array( 'attribute' => 'date_field', 'from' => '2010-09-10', ), )); Below is the full filter condition codes with attribute code and its sql equivalent eq : = neq : != like : LIKE nlike : NOT LIKE in : IN () nin : NOT IN () is : IS notnull : IS NOT NULL null : IS NULL moreq : >= gt : > lt : < gteq : >= lteq : <= finset : FIND_IN_SET() from : >= (for use with dates) to : <= (for use with dates) date : optional flag for use with from/to to specify that comparison value should first be converted to a date datetime : optional flag for use with from/to to specify that comparison value should first be converted to a datetime addFieldToFilter: alias for addAttributeToFilter(). This filters the database table fields. /** * Wrapper for compatibility with Varien_Data_Collection_Db * * @param mixed $attribute * @param mixed $condition */ addFieldToFilter($attribute, $condition=null)

addAttributeToSort: adds ORDER BY clause on $attribute /** * Add attribute to sort order * * @param string $attribute * @param string $dir * @return Mage_Eav_Model_Entity_Collection_Abstract */ addAttributeToSort($attribute, $dir=asc) addExpressionAttributeToSelect: adds SQL expression $expression, using $alias, to SELECT clause (typically containing aggregate functions such as SUM(), COUNT()); when $attribute specifies a single attribute as a string, $expression can reference the attribute as simply {{attribute}}, but when passing an array of attributes, each attribute must be referenced in $expression by the name of the specific attribute; /** * Add attribute expression (SUM, COUNT, etc) * * Example: (sub_total, SUM({{attribute}}), revenue) * Example: (sub_total, SUM({{revenue}}), revenue) * * For some functions like SUM use groupByAttribute. * * @param string $alias * @param string $expression * @param string $attribute * @return Mage_Eav_Model_Entity_Collection_Abstract */ addExpressionAttributeToSelect($alias, $expression, $attribute) groupByAttribute: adds $attribute to GROUP BY clause /** * Groups results by specified attribute * * @param string|array $attribute */ groupByAttribute($attribute) joinAttribute: joins another entity and adds attribute from joined entity, using $alias, to SELECT clause. Here are the parameters for joinAttribute function:$alias = selected field name. You can keep its name whatever you want. $attribute = joined entity type code and attribute code = entity_type_code/attribute_code entity_type_code is present in eav_entity_type table attribute_code is present in eav_attribute table attribute_code is attribute of the corresponding entity you want to select out.

$bind = attribute code of the main entity to link to the joined entity. $filter = primary key for the joined entity (entity_id default) /** * Add attribute from joined entity to select * * Examples: * (billing_firstname, customer_address/firstname, default_billing) * (billing_lastname, customer_address/lastname, default_billing) * (shipping_lastname, customer_address/lastname, default_billing) * (shipping_postalcode, customer_address/postalcode, default_shipping) * (shipping_city, $cityAttribute, default_shipping) * * Developer is encouraged to use existing instances of attributes and entities * After first use of string entity name it will be cached in the collection * * @todo connect between joined attributes of same entity * @param string $alias alias for the joined attribute * @param string|Mage_Eav_Model_Entity_Attribute_Abstract $attribute * @param string $bind attribute of the main entity to link with joined $filter * @param string $filter primary key for the joined entity (entity_id default) * @param string $joinType inner|left * @return Mage_Eav_Model_Entity_Collection_Abstract */ joinAttribute($alias, $attribute, $bind, $filter=null, $joinType=inner, $storeId=null) joinTable: joins table $table Here are the parameters of the function joinTable:$table = table name to join $bind = ( parent_key = foreign_key ) $fields = array of fields to select $cond = where condition $joinType = join type /** * Join a table * * @param string|array $table * @param string $bind * @param string|array $fields * @param null|array $cond * @param string $joinType * @return Mage_Eav_Model_Entity_Collection_Abstract */ joinTable($table, $bind, $fields=null, $cond=null, $joinType=inner) Using joinAttribute and joinTable In the code below, all order invoice items are selected, i.e. all products that have been invoiced.

joinTable is used to join sales_order_entity table to fetch increment_id and store_id of the invoice for each product. joinAttribute is used to fetch order_id, product_name, and store_id. joinTable is used again to fetch the order status of each invoice item. $collection = Mage::getModel('sales/order_invoice_item') ->getCollection() ->joinTable('sales_order_entity', 'entity_id=parent_id', array('invoice_id'=>'increment_id', 'store_id' => 'store_id'), null , 'left') ->joinAttribute('order_id', 'invoice/order_id', 'parent_id', null, 'left') ->joinAttribute('product_name', 'invoice_item/name', 'entity_id', null, 'left') ->joinAttribute('store_id', 'invoice/store_id', 'parent_id', null, 'left') ->joinTable('sales_order', 'entity_id=order_id', array('order_status'=>'status'), null , 'left') ; joinField: joins regular table field using an attribute as foreign key /** * Join regular table field and use an attribute as fk * * Examples: * (country_name, directory/country_name, name, country_id=shipping_country, {{table}}.language_code=en, left) * * @param string $alias country_name * @param string $table directory/country_name * @param string $field name * @param string $bind PK(country_id)=FK(shipping_country_id) * @param string|array $cond {{table}}.language_code=en OR array(language_code=>en) * @param string $joinType left * @return Mage_Eav_Model_Entity_Collection_Abstract */ joinField($alias, $table, $field, $bind, $cond=null, $joinType=inner) removeAttributeToSelect: removes $attribute from SELECT clause; specify null to remove all attributes /** * Remove an attribute from selection list * * @param string $attribute * @return Mage_Eav_Model_Entity_Collection_Abstract */ removeAttributeToSelect($attribute=null) setPage: sets LIMIT clause by specifying page number (one-indexed) and number of records per page; equivalent to calling setCurPage($pageNum) and setPageSize($pageSize) /** * Set collection page start and records to show * * @param integer $pageNum * @param integer $pageSize

* @return Mage_Eav_Model_Entity_Collection_Abstract */ setPage($pageNum, $pageSize) importFromArray: imports 2D array into collection as objects /** * Import 2D array into collection as objects * * If the imported items already exist, update the data for existing objects * * @param array $arr * @return Mage_Eav_Model_Entity_Collection_Abstract */ importFromArray($arr) exportToArray: returns collection data as a 2D array /** * Get collection data as a 2D array * * @return array */ exportToArray() setOrder: alias for addAttributeToSort() q.v., identical except that it can accept array of attributes, and default $dir is desc /** * Set sorting order * * $attribute can also be an array of attributes * * @param string|array $attribute * @param string $dir * @return Mage_Eav_Model_Entity_Collection_Abstract */ setOrder($attribute, $dir=desc)
Tng quan: Gii thiu cc th mc trong magento

* APP: Th mc cha tt c cc file lin quan ti cc module, template, cc file run h thng * Downloader: Th mc lu tr tt c cc module c download v bng magentoconnect ( Install module online) * Errors: Th mc cha file lin quan ti cc thng bo li. * Includes: Chn cc file m rng khc. * JS: Cha tt c cc file js ca h thng * LIB: Cha cc file h thng, zend * Media: cha cc file hnh nh ca website. * pkginfor: Thng tin gi sn phm * SHELL: cc file lin quan ti reindex * skin: chc cc file css, javascript, image cho template * VAR: cha cc file lin quan ti cache, export Bc 1: t tn template

to ra 1 b template cho mnh theo tn mnh thch cc bn lm nh sau: 1. Copy ton b th mc default trong base qua th mc default bn di (mu vng th ). 2. i tn thnh tn mnh thch, gi s y ti i tn thnh magentovietnam 3. Qua th mc skin v lm tng t nh trn, bn s thy kt qu ging trong hn h trn Bc 2: Qui nh template hin th trn website: Cc bn lm nh sau: 1. login vo admin 2. Trn menu bn chn H thng --> Cu hnh --> Thit k giao din 3. Nhp tn template vo mc nh 4. Chn Lu ci t

y l cc bc c bn trong vic thay i template cho magento

addAttributeToFilter Conditionals In Magento

Posted on April 16, 2010 by BT | There have been 11 comment(s) addAttributeToFilter is a function that can be called on a product collection in Magento. In short, it adds a condition to the WHERE part of the MySQL query used to extract a product collection from the database.
? 1$_products = Mage::getModel('catalog/product')->getCollection() 2 3 4
->addAttributeToSelect(array('name', 'product_url', 'small_image')) ->addAttributeToFilter('sku', array('like' => 'UX%')) ->load();

The above code would get a product collection, with each product having it's name, url, price and small image loaded in it's data array. The product collection would be filtered and contain only products that have an SKU starting with UX.

addAttributeToFilter Conditionals
Notice above, I used the LIKE operator? There are many more operators in SQL and addAttributeToFilter will accept them all. I include them below as well as a reference for you. Hopefully this will save you some time. Equals: eq
? 1$_products->addAttributeToFilter('status', array('eq' => 1));

Not Equals - neq


? 1$_products->addAttributeToFilter('sku', array('neq' => 'test-product'));

Like - like
? 1$_products->addAttributeToFilter('sku', array('like' => 'UX%'));

One thing to note about like is that you can include SQL wildcard characters such as the percent sign. Not Like - nlike
?

1$_products->addAttributeToFilter('sku', array('nlike' => 'err-prod%'));

In - in
? 1$_products->addAttributeToFilter('id', array('in' => array(1,4,74,98)));

When using in, the value parameter accepts an array of values. Not In - nin
? 1$_products->addAttributeToFilter('id', array('nin' => array(1,4,74,98)));

NULL - null
? 1$_products->addAttributeToFilter('description', 'null');

Not NULL - notnull


? 1$_products->addAttributeToFilter('description', 'notnull');

Greater Than - gt
? 1$_products->addAttributeToFilter('id', array('gt' => 5));

Less Than - lt
? 1$_products->addAttributeToFilter('id', array('lt' => 5));

Greater Than or Equals To- gteq


? 1$_products->addAttributeToFilter('id', array('gteq' => 5));

Less Than or Equals To - lteq


? 1$_products->addAttributeToFilter('id', array('lteq' => 5));

addFieldToFilter()
As far as I'm aware, addAttributeToFilter only works with products in Magento. When I first found out this fact I was not only shocked, I was worried! I thought that without it, I would have to custom craft all of my SQL queries. After scouring the Magento core code one night, I found addFieldToFilter(). This functions works in the exact same way and takes the same paramters, however it works on ALL collections and not just on products!

Debugging The SQL Query


There are two ways to debug the query being executed when loading a collection in Magento.
? 1// Method 1 2Mage::getModel('catalog/product')->getCollection()->load(true); 3 4// Method 2 (Quicker, Recommended) 5$collection = Mage::getModel('catalog/product')->getCollection(); 6
echo $collection->getSelect();

Both method 1 and method 2 will print out the query but both will do it in slightly different ways. Method 1 prints the query out as well as loading the products while method 2 will just convert the query object to a string (ie. will print out the SQL). The second method is definitely better as it will be executed much quicker but I include them both here for reference. On a side note, I will soon be writing an article on the getSelect() function as it opens up a door in Magento Collections that gives them (and you) true power!
Magento c mt function rt hay, l Event Observer. Magento thit k theo Observer Event Pattern cho h thng hook ca h, v vi h thng Event Observer Hook ny, cc chc nng b sung c th c thm vo hoc sa i m khng cn sa i core. Danh sch y Magento Observer Hook cc bn c th tham kho thm ti y: http://www.nicksays.co.uk/magento_events_cheat_sheet/ Cc m t v v d v Observer Event v cch ghi controller c a ra ti y: http://www.magentocommerce.com/wiki...stomizing_magento_using_event-observer_method

T cc lin kt ngay pha trn, bn c th tm thy v d lm th no bn c th to v s dng Observer Event trong Magento. Trong bi vit ny, bn s thy lm th no bn c th s dng Observer Event trc v sau khi bt k s kin no trong Magento. Mt v d s l s kin catalog_product_save_before s c dng bi Magento trc khi sn phm c lu. Tng t nh vy, c mt s kin catalog_product_save_after c dng bi Magento ngay lp tc sau khi sn phm c lu. y, chng ta c th thm s kin ty chnh ca mnh trc khi v sau khi bt k s kin no ti core ca Magento. Bng cch ny, chng ta khng cn s dng cc dispatch event. Bng cch ny, thm s kin ty chnh trc v sau khi lu lun hu ch khi chng ta ch cn thm hoc lm mt ci g trc khi hoc sau khi bt k s kin no ca core Magento. V d, thit lp mt s gi tr cho mt s thuc tnh trc hoc sau khi sn phm c lu. i vi iu ny, bn ch cn b sung thm mt s Event Observer code trong module ca bn ti YourModule/etc/config.xml v thm mt observer mi ti YourModule/Model/Observer.php Trong on code v d di y, ti thm vo trc v sau khi ly s kin cho a ch khch hng v danh mc sn phm. Ti Customer Address, s kin hook chy trc v sau khi lu a ch khch hng v Catalog Product, hook chy trc v sau khi sn phm lu trong admin. customer_address_save_before = chy trc khi lu a ch khch hng customer_address_save_after= chy ngay lp tc sau khi lu a ch khch hng catalog_product_save_before = chy ngay trc khi lu sn phm catalog_product_save_after = chy ngay sau khi lu sn phm V y l code: config.xml

PHP:
<global> <events> <customer_address_save_before> <observers> <yourmodule> <type>singleton</type> <class>yourmodule/observer</class> <method>customer_address_save_before</method> </yourmodule> </observers> </customer_address_save_before>

<customer_address_save_after> <observers> <yourmodule> <type>singleton</type> <class>yourmodule/observer</class> <method>customer_address_save_after</method> </yourmodule> </observers> </customer_address_save_after>

<catalog_product_save_before> <observers> <yourmodule> <type>singleton</type> <class>yourmodule/observer</class> <method>catalog_product_save_before</method> </yourmodule> </observers> </catalog_product_save_before>

<catalog_product_save_after> <observers> <yourmodule> <type>singleton</type> <class>yourmodule/observer</class> <method>catalog_product_save_after</method> </yourmodule>

</observers> </catalog_product_save_after> </events> </global>


Observer.php

PHP:
<?php class YourNamespace_YourModule_Model_Observer { public function customer_address_save_before($observer) { $address = $observer->getCustomerAddress(); //echo "<pre>"; print_r($address->getData()); exit; // do something here } public function customer_address_save_after($observer) { $address = $observer->getCustomerAddress(); //echo "<pre>"; print_r($address->getData()); exit; // do something here } public function catalog_product_save_before($observer) { $product = $observer->getProduct(); //echo "<pre>"; print_r($product->getData()); exit; // do something here } public function catalog_product_save_after($observer)

{ $product = $observer->getProduct(); //echo "<pre>"; print_r($product->getData()); exit; // do something here } } ?>


Tng t, cc bn c th thm cc tu chnh ca mnh vi cc s kin khc nh sales_order_save_before,sales_order_save_after, sales_order_invoice_save_before, sales_order_invoice_save_after...

Das könnte Ihnen auch gefallen