如何基于一天(而不是日期)过滤集合?

时间:2015-10-13 13:39:21

标签: php database magento entity-attribute-value

此处的最终目标是获取今天生日的客户列表,并向他们发送优惠券代码(也以编程方式完成)。

要做到这一点,我今天需要抓住所有客户的生日。在SQL中,我会将date转换为日期和月份并查询,但我不确定如何在集合中执行此操作。目前我有:

$collection = Mage::getResourceModel('customer/customer_collection')
        ->joinAttribute('dob','customer/dob', 'entity_id');
        ->addAttributeToFilter('dob', '2015-10-02 00:00:00');

这仅适用于2015年2月10日持有DOB的人。在这个例子中,我需要匹配每个人的出生日期,即10月2日,而不仅仅是2015年10月2日。那么,我如何省略年份,只包括日期和月份?

我已经能够使用LIKE来实现这一点,但这似乎没有得到优化,我想假设有更好的方法:

$collection = Mage::getResourceModel('customer/customer_collection')
        ->joinAttribute('dob','customer/dob', 'entity_id')
        ->addAttributeToFilter('dob', array('like' => '%-10-02 00:00:00'));

2 个答案:

答案 0 :(得分:0)

一个简单的解决方案就像这个实现查询一样根据你的需要逻辑在这里:

SELECT
  emp_firstname AS first_name,
  emp_lastname AS last_name,
  emp_birthday AS dob
FROM
  emp
WHERE
  MONTH(emp_birthday)=MONTH(CURDATE())
  AND DAY(emp_birthday)=DAY(CURDATE())
or if you want to consider also leap years, you could use this:

SELECT
  emp_firstname AS first_name,
  emp_lastname AS last_name,
  emp_birthday AS dob
FROM
  emp
WHERE
  emp_birthday +
    INTERVAL
      YEAR(CURDATE())-YEAR(emp_birthday) +
      (MONTH(emp_birthday)<MONTH(CURDATE())
       OR (MONTH(emp_birthday)=MONTH(CURDATE()) AND DAY(emp_birthday)<DAY(CURDATE())))
    YEAR = CURDATE()
If someone's date of birth is on 29th of February, and today is 28th of February and this year is not a leap year, my last query will consider his/her birthday as today.

My second query could be also simplified like this:

SELECT
  emp_firstname AS first_name,
  emp_lastname AS last_name,
  emp_birthday AS dob
FROM
  emp
WHERE
  (MONTH(emp_birthday)=MONTH(CURDATE())
  AND DAY(emp_birthday)=DAY(CURDATE()))
  OR (DAY(LAST_DAY(emp_birthday))=29
      AND DAY(emp_birthday)=29
      AND DAY(LAST_DAY(CURDATE()))=28);

答案 1 :(得分:0)

solution:


require_once '../app/Mage.php';
Mage::app();

$currentDate = date('Y-m-d H:i:s');
$customerCollection = Mage::getResourceModel('customer/customer_collection')
        ->addNameToSelect()
        ->addAttributeToSelect('*')
        ->addAttributeToFilter('dob', array('lteq' => $currentDate));


foreach ($customerCollection as $customer) {
    $active = $customer->getIsActive();
    if($active == 1){
        //echo 'customer Dob => '.$customer->getDob().'<br>';
        $customerDob = $customer->getDob();
        $customerId = $customer->getId();
        $date =  date('d/m',  strtotime($customerDob));
        echo $customerId.' => '.$date.'<br>';
    }

}