14Jul/105

Filter Magento product collection using addAttributeToFilter() to create SQL OR(s)

/** 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%'),
     * )
*/
// Correct application looks like this
$_productCollection->addAttributeToFilter(
				array(
					array('attribute'=>'name', 'like'=>'%productname%'),
					array('attribute'=>'sku', 'like'=>'%productsku%')
				)
			);

About John Webber

John is the founder of MagThemes.com and has been working with Magento since version 0.9
Comments (5) Trackbacks (0)
  1. Is it possible to filter products based on the website they’re assigned to? Is there some documentation available somewhere that lists which attributes are available for filtering?

  2. aaa i’got a problem,

    i’ve got 1 instead of having the name of my field but it seems to work.

    for example:
    “SELECT `main_table`.* FROM `amer_program_code` AS `main_table` WHERE (((1 = ’8′) or (1 = ’8′)))”

    :(

    • benjion,

      Please take a look at your code again and make sure it is exactly as we have it. It is important that you keep the arrays exactly as shown. I noticed that you have too many parentheses around your WHERE clause. I’m going out on a limb here but the 1 could come from a missing key in the array, e.g. array('attribute', 'eq' => '8') or something similar. It should be array('attribute' => 'name', 'eq' => '8').
      I made some tests on my development system and this does NOT work properly for me.
      Perhaps if you show us the code, we can figure out what is going wrong here.


Leave a comment


No trackbacks yet.