I have the following function which gives me a list of simple products which are on special at the moment:
public function getSpecialProducts($config = [])
{
/** @var $collection \Magento\Catalog\Model\ResourceModel\Product\Collection */
$collection = $this->_productCollectionFactory->create();
if(isset($config['categories'])){
$collection->joinField(
'category_id', $this->_resource->getTableName('catalog_category_product'), 'category_id',
'product_id = entity_id', null, 'left'
)
->addAttributeToFilter('category_id', array(
array('finset' => $config['categories']),
));
}
$collection->setVisibility($this->_catalogProductVisibility->getVisibleInCatalogIds())
->addAttributeToSelect('*')
->addStoreFilter()
->addMinimalPrice()
->addUrlRewrite()
->addTaxPercents()
->addFinalPrice();
$collection->setPageSize(isset($config['pagesize'])?$config['pagesize']:5)
->setCurPage(isset($config['curpage'])?$config['curpage']:1)
->getSelect()->group("e.entity_id");
$collection->getSelect()->where('price_index.final_price < price_index.price');
return $collection;
But it totally ignores the mother product if the child product is on special.
So I tried to use this function instead:
public function getDealsProducts($config = [])
{
$todayStartOfDayDate = $this->_localeDate->date()->setTime(0, 0, 0)->format('Y-m-d H:i:s');
$todayEndOfDayDate = $this->_localeDate->date()->setTime(23, 59, 59)->format('Y-m-d H:i:s');
/** @var $collection \Magento\Catalog\Model\ResourceModel\Product\Collection */
$collection = $this->_productCollectionFactory->create();
if(isset($config['categories'])){
$collection->joinField(
'category_id', $this->_resource->getTableName('catalog_category_product'), 'category_id',
'product_id = entity_id', null, 'left'
)
->addAttributeToFilter('category_id', array(
array('finset' => $config['categories']),
));
}
$collection->setVisibility($this->_catalogProductVisibility->getVisibleInCatalogIds())
->addAttributeToSelect('*')
->addStoreFilter()->addAttributeToFilter(
'special_from_date',
[
'or' => [
0 => ['date' => true, 'to' => $todayEndOfDayDate],
1 => ['is' => new \Zend_Db_Expr('null')],
]
],
'left'
)->addAttributeToFilter(
'special_to_date',
[
'or' => [
0 => ['date' => true, 'from' => $todayStartOfDayDate],
1 => ['is' => new \Zend_Db_Expr('not null')],
]
],
'left'
)->addAttributeToFilter(
[
['attribute' => 'special_from_date', 'is' => new \Zend_Db_Expr('not null')],
['attribute' => 'special_to_date', 'is' => new \Zend_Db_Expr('not null')],
]
)->addAttributeToSort(
'special_from_date',
'desc'
)
->setPageSize(isset($config['pagesize'])?$config['pagesize']:5)
->setCurPage(isset($config['curpage'])?$config['curpage']:1)
->getSelect()->group("e.entity_id");
return $collection;
}
But it is also not getting me to where I want to be.
I am new in magento 2. Please help