Reputation: 721
I've got this problem that I can't solve. Partly because I can't explain it with the right terms. I'm new to this so sorry for this clumsy question.
Below you can see an overview of my goal.
In my custom module i wrote code like this
<?php
$userId=Mage::getSingleton('customer/session')->getCustomer()->getId();
$collection = Mage::getResourceModel('partners/userdata');
$collection->getSelect()->where('userid ='.$userId );
?>
Using this i'm getting all products of the current logged in customer.
But my plan is have to get the product names starts with a letter 'h
'.
Any Ideas ?
Upvotes: 0
Views: 1229
Reputation: 691
You should try to avoid using getSelect outside of collection class methods. Instead of getSelect you should use collection filters, like this:
$collection = Mage::getModel('partners/userdata')->getCollection();
$collection->addFieldToFilter('userid', $userId);
It will prevent SQL injections, and wrap value with correct quotes. There is a lot of different condition operations available, all listed here - http://www.magentocommerce.com/knowledge-base/entry/magento-for-dev-part-8-varien-data-collections, section "Other Comparison Operators" .
In your case you need to use product collection and operation 'like'
$collection->addFieldToFilter('name', array('like' => 'h%'));
But there is a tricky thing about product collections. The product model implement EAV model, which means there that product it self it's entity (in terms of magento) and all it's fields are attributes (so it's stored in specific way and processed differently) so for product collection you should use addAttributeToFilter, instead of addFieldToFilter. So complete code will looks like:
$collection = Mage::getModel('catalog/product')->getCollection();
$collection->addAttributeToFilter('name', array('like' => 'h%'));
It seems to be confused, because it's related to Magento ORM implementation, and I never seen something like this in other products/frameworks. So, to simplify you can always use addAttributeToFilter, and if you get an error which says method not exists, replace it with addFieldToFilter.
If you need some condition which is not available in core implementation, or it just often used in your code you can define additional method for collection.
Upvotes: 1