Reputation: 2461
I have an attribute defined for a product that will contain a comma separated list of values. The idea behind this is so that I can cross reference this product against another product.
pseudo code would look a little like this: Find all products where the attribute "cross_ref" is like '%1234%'
The cross_ref attribute will contain something like "1234,5678,abcd" etc I've tried the following but it doesn't return any products:
$collection = Mage::getModel('catalog/product')->getCollection();
$collection->addAttributeToSelect('*');
$collection->addFieldToFilter('cross_ref',array('like'=> '1234'));
//$collection->addAttributeToFilter('cross_ref',array('like'=> '1234')); // This didn't work either
foreach ($collection as $product) {
var_dump($product->getData());
}
This code doesn't return anything though.
Any ideas how I can achieve this?
Thank you
Upvotes: 1
Views: 3864
Reputation: 2058
Looks like you forgot the % sign to match a subpart of the string: 'like' => '%1234%'
.
However, if you don't want 1234 to match 12345, you might want to include the comma in the query, and also allow for no commas in the beginning or end of the string:
$collection->addFieldToFilter('cross_ref', array(
array('like'=> '%,1234,%'),
array('like'=> '1234,%'),
array('like'=> '%,1234'),
));
Upvotes: 4