0

私は、ユーザーが休暇期間を選択できるWebアプリを作成しています。彼は一度にすべての週を選択する必要がないので、HolidayPeriodモデルのsave()メソッドで(トランザクション内で)連続する休日期間を融合しています。

私の問題は、HolidayPeriodのrules()の検証の1つが、新しい期間が既存の期間と重複していないことです。したがって、私の実際のコードは次のとおりです。

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);

そして、エコーの両方の呼び出しは、開始時と終了時に同じ番号を出力します。

delete()の後に$ this-> user-> holidayPeriodsを更新するにはどうすればよいですか?

ありがとう

4

2 に答える 2

1

「$this->user->holidayPeriods」からは何も削除していません。これを行うことにより、の値を変数「$periods」に$periods=$this->user->holidayPeriods;渡すだけです。$this->user->holidayPeriodsしたがって、「$ period」を変更しても、何もしません$this->user->holidayPeriods。したがって、次のようなものを試してください。

 foreach($this->user->holidayPeriods as $period){
    if ($this->isConsecutiveWith($period)){
       $this->fusion($period);
     } 
 }
于 2012-05-20T03:00:44.480 に答える
1

delete()の後に$ this-> user-> holidayPeriodsを更新するにはどうすればよいですか?

(これがで定義された関係であると仮定しrelations()ます)次のことができます。

  • unset($this->user->holidayPeriods)-次にアクセスするときに$this->user->holidayPeriods、DBからロードされます。
  • $this->user->getRelated('holidayPeriods', true)holidayPeriods-関係をDBから強制的に更新します。
  • DBからの更新は完全に避けてください。
    
    $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);
    
于 2012-05-20T04:21:15.380 に答える