我正在做一个网络应用程序,用户可以在其中选择他们的假期。由于他不需要一次选择所有星期,因此我将连续的假期融合在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);
并且两个回显调用在开头和结尾打印相同的数字。
如何在 delete(( 之后更新$this->用户->假期周期?
谢谢
如何在 delete(( 之后更新$this->用户->假期周期?
(假设这是 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);
您不会从"$this->user->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);
}
}