Where is the special_price/special_to_date/special_from_date held at?
-
13-12-2019 - |
Question
I have a query for the catalog/product model and that has an associated properties of special price field, I can access them normally by using the model, however when using getSelect()
it will only get me the table catalog_product_entity
, which does not contain what I need.
Here is what I am using:
$products = Mage::getResourceModel('catalog/product_collection')
->getSelect()
->where(
" ( special_from_date > '$todayDate' OR special_to_date < '$todayDate' )
OR ( special_from_date IS NULL AND special_to_date IS NULL ) ");
->query();
As you might expect this will return the column not found error.
Oh and if you are wondering, why don't I just use filters? The issue is that Its very ugly to create a filter with the combination (V OR V) OR (V AND V)
Solution
Try it like this:
$todayStartOfDayDate = Mage::app()->getLocale()->date()
->setTime('00:00:00')
->toString(Varien_Date::DATETIME_INTERNAL_FORMAT);
$todayEndOfDayDate = Mage::app()->getLocale()->date()
->setTime('23:59:59')
->toString(Varien_Date::DATETIME_INTERNAL_FORMAT);
$products = Mage::getResourceModel('catalog/product_collection')
->addAttributeToSelect(array('special_price', 'special_to_date', 'special_from_date'))
->addAttributeToFilter(
'special_from_date',
array(
'or'=> array(
0 => array(
'date' => true,
'to' => $todayEndOfDayDate
),
1 => array(
'is' => new Zend_Db_Expr('null')
)
)
),
'left'
)
->addAttributeToFilter(
'special_to_date',
array(
'or'=> array(
0 => array(
'date' => true,
'from' => $todayStartOfDayDate
),
1 => array(
'is' => new Zend_Db_Expr('null')
)
)
),
'left'
)
->addAttributeToFilter(
array(
array(
'attribute' => 'special_from_date',
'is'=>new Zend_Db_Expr('not null')
),
array(
'attribute' => 'special_to_date',
'is'=>new Zend_Db_Expr('not null')
)
)
);
This should get you the list of products that have a valid special price today. I assume that's what you want.
OTHER TIPS
This is the code I derivated from @Marius 's answer
$products = Mage::getResourceModel('catalog/product_collection')
->addAttributeToFilter(
array(
array(
'attribute' =>'special_from_date',
'date' => true,
'gt' => $todayDate
),
array(
'attribute' =>'special_to_date',
'date' => true,
'lt' => $todayDate
),
'or' => array(
'attribute' =>'special_from_date',
'date' => true,
'null' => true,
'and' => array(
'attribute' =>'special_to_date',
'date' => true,
'null' => true
)
)
)
);
And it works !