Articles tagged with: collection
This article shows how we can get list of all categories from current product or any particular product as well.
Both ways (Dependency Injection & Object Manager way) are shown below:
This article shows how we can get product collection in Magento 2.
Using Dependency Injection (DI)
Below is a block class of my custom module (Chapagain_HelloWorld). I have injected object of \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory class in the constructor of my module’s block class.
I had added a new product attribute. Suppose the attribute code is ‘test’. I have been trying to fetch/select that newly added product attribute. Here is my Magento collection code:-
$collection = Mage::getModel('catalog/product')
Here is a quick tip to add OR query and AND query to collection object. I am implementing this on product collection.
Getting product collection
You have created a custom module.
You have entered certain data in your database.
You need to show the data randomly.
There are different important functions that you can implement in your Collection object. The functions are present in Varien_Data_Collection_Db class. The class file is present in lib/Varien/Data/Collection/Db.php
Here are some of the functions that you can use in your collection object:-
Suppose, you have a product collection and you want to filter it by category. Suppose, you want to filter it by more than one category. You can use addCategoryFilter if you have only one category. But, what if you want to filter by more than one category?
Category ids are stored for product in a comma separated way. So, to filter product collection by more than one category, you have to use: