I’m doing a webapp where the user can choose their holiday periods. Since he doesn’t need to select all the weeks at once I’m fusioning consecutive holiday periods in the
save() method of the HolidayPeriod model (within a transaction).
My problem is that one of the validation in the rules() of HolidayPeriod is that the new period doesn’t overlap with any existing period. So my actual code is:
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>";
}
}
The problem there is that when calling parent::save($runValidation, $attributes) the validation detects the deleted periods as overlapped and it fails. So I made a simple test:
$periods=$this->user->holidayPeriods;
echo count($periods);
foreach($periods as $period){
$period->delete();
}
echo count($this->user->holidayPeriods);
And both calls to echo print the same number at the start and at the end.
How can I make the $this->user->holidayPeriods to be updated after the delete()?
Thanks
(Assuming this is a relation defined in
relations()) You can:unset($this->user->holidayPeriods)– the next time you access$this->user->holidayPeriods, it will be loaded from the DB.$this->user->getRelated('holidayPeriods', true)– forces theholidayPeriodsrelation to be refreshed from the DB right there.