Yii交易和验证问题

时间:2012-05-19 23:29:53

标签: php mysql yii

我正在做一个用户可以选择假期的网络应用程序。由于他不需要一次性选择所有周,所以我正在融合连续的假期 HolidayPeriod模型的save()方法(在事务中)。

我的问题是HolidayPeriod规则()中的一个验证是新时段与任何现有时段都不重叠。所以我的实际代码是:

public function save($runValidation = true, $attributes = null)
{
    $ts = Yii::app()->db->beginTransaction();
    try {
       $periods=$this->user->holidayPeriods;
       foreach ($periods as $period){
            if ($this->isConsecutiveWith($period)){
                $this->fusion($period);
            } 
       }
       if ($result = parent::save($runValidation, $attributes)) {

         ....................
         ....................


private function fusion($period){
    $this->start=date('Y-m-d',min(strtotime($this->start),strtotime($period->start)));
    $this->end=date('Y-m-d',max(strtotime($this->end),strtotime($period->end)));
    if (!$period->delete()){
        echo "FAIL<BR>";
        throw new Exception();
    }else {
        echo "OK<BR>";          
    }   
}

问题在于,当调用 parent :: save($ runValidation,$ attributes)时,验证会将已删除的句点检测为重叠且失败。所以我做了一个简单的测试:

 $periods=$this->user->holidayPeriods;
 echo count($periods);
 foreach($periods as $period){
     $period->delete();
 }
 echo count($this->user->holidayPeriods);

echo 的两次调用都会在开头和结尾打印相同的数字。

如何在delete()之后更新$ this-&gt; user-&gt; holidayPeriods?

由于

2 个答案:

答案 0 :(得分:1)

您不会删除“$ this-&gt; user-&gt; holidayPeriods”中的任何内容。通过这样做:$periods=$this->user->holidayPeriods;您只将$this->user->holidayPeriods的值传递给变量“$ periods”。因此,当您修改“$ periods”时,您没有对$this->user->holidayPeriods做任何事情。所以尝试这样的事情:

 foreach($this->user->holidayPeriods as $period){
    if ($this->isConsecutiveWith($period)){
       $this->fusion($period);
     } 
 }

答案 1 :(得分:1)

  

如何在delete()之后更新$ this-&gt; user-&gt; holidayPeriods?

(假设这是relations()中定义的关系)您可以:

  • unset($this->user->holidayPeriods) - 下次访问$this->user->holidayPeriods时,它将从数据库加载。
  • $this->user->getRelated('holidayPeriods', true) - 迫使holidayPeriods关系从数据库中刷新。
  • 完全避免从数据库刷新:
    
    $periods = $this->user->holidayPeriods;
    foreach ($periods as $ix => $period){
      if ($this->isConsecutiveWith($period)){
        $this->fusion($period);
        unset($periods[$ix]);
      }
    }
    $periods = array_values($periods); // fix period indexes
    unset($this->user->holidayPeriods);
    $this->user->addRelatedRecord('holidayPeriods', $periods, false);