【问题标题】:Sort the $results array from the afterFind callback by calculated field?按计算字段对 afterFind 回调中的 $results 数组进行排序?
【发布时间】:2013-05-08 07:21:11
【问题描述】:

第一个问题,我有一点点蛋糕的经验,但我还远远不够精通。在我的模型 - 产品中,我使用 afterFind 回调进行一些计算。 首先,它检查产品的保修期是否仍然有效(startDate +warranty_period),然后计算保修期还剩多少。 为此,我使用:

$future = '+'.$results[$key]['Product']['warranty_period'].'months';    
$startDate = $results[$key]['Product']['created'];
$endDate = date('Y-m-d', strtotime($future, strtotime($startDate)));
$curDate = date('Y-m-d');

if($endDate > $curDate){
$date1 = new DateTime($endDate);
$date2 = new DateTime($curDate);
$interval = $date1 -> diff($date2);

默认情况下,$interval 以数字字符串的形式返回,例如“01119”。 然后我运行下面的代码来输出它:0年,11个月,19天。

//years     
if($interval->y > 0){
$years = $interval->y.' years, ';
}
//months        
if($interval->m > 0){
$months = $interval->m.' months, ';
}
//days
if($interval->d > 0){
$days = $interval->d.' days';
}
$results[$key]['Product']['warranty_time'] = $years.$months.$days;
}else{
$results[$key]['Product']['warranty_time'] = 'Expired';
}

然后将这些计算的结果传递到 afterFind 返回的 $results 数组中。 这是我的实际问题:我将如何根据剩余的保修时间对 $results 数组进行排序?

我在其他一些字段上使用 Paginator,使用 echo $this->Paginator->sort('name', Name); 这可以很好地对记录 ASC 或 DESC 进行快速排序,但我无法让它与我的warranty_time 字段一起使用。我怀疑这可能是因为 cake 将 $interval 视为字符串,而不是 int 或其他数字数据类型。

我认为 $interval 似乎作为“数字”返回,例如“01119”,是否可以根据该数字对数组进行排序,然后在视图中进行格式化?这样做的最佳方法是什么?

【问题讨论】:

    标签: cakephp sorting cakephp-2.0


    【解决方案1】:

    我认为最简单的方法可能是在数据库中 - 像这样:

    $data = $this->MyModel->find('all', array('order' => 
        array('end_date - start_date' => 'DESC')));
    

    显然这不适合您,但您应该能够使用 MySQL 的 DATE_ADD 之类的方法来计算保修结束日期等。

    希望这会有所帮助。

    【讨论】:

    • 谢谢,我改变了它,以便在将新记录添加到表之前完成计算,以便将值实际保存到数据库中,这样我就可以运行正常的 SQL ORDER,如以及其他有用的东西,例如查找在某些日期之间过期的产品等。您的回答起初对我没有帮助,但经过大量研究后,我发现按计算字段排序通常会成为一个问题正在调用数千条记录,这导致我以相反的方式做事。再次感谢您好心的先生。
    • 没问题,很高兴它(间接)有帮助!
    猜你喜欢
    • 2016-01-11
    • 2015-03-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-07
    • 2014-10-01
    • 1970-01-01
    相关资源
    最近更新 更多