有没有办法将int列中的值减去1?我有一个按钮,单击它时会调用一个函数来保存表中的数据,但我想知道如何减去一个使用yii 2的数据库中的数字我已经尝试了下面的代码,但它没有任何效果。有人能帮助我如何在yii 2中进行数学运算吗?
public static function AddSubject($subjectid, $clientid){
$subject = ActiveCurriculum::findOne(['subjectid' => $subjectid]);
$activesubject = new ActiveSubject();
$activesubject->clientid = $clientid;
$activesubject->subjectid = $subject->subjectid;
$activesubject->subjectcode = $subject->subjectcode;
$activesubject->days = $subject->days;
$activesubject->time = $subject->time;
$activesubject->section = $subject->section;
$activesubject->room = $subject->room;
$activesubject->units = $subject->units;
$subject->units = $subject->units - 1; //this should subtract the number
//of slots by 1 but now it is not working.
$activesubject->save();
return true;
//return static::findOne(['subjectid' => $subjectid]);
//->where(['subjectid' => $subjectid]);
}
答案 0 :(得分:0)
当您对AR对象进行了一些更改并希望保存更改时,您应该执行->save()
:
$subject->units = $subject->units - 1;
$subject->save();
看起来你只是忘了那样做。
答案 1 :(得分:0)
您可以使用以下内容大规模复制属性,然后保存新模型:
public static function AddSubject($subjectid, $clientid){
$subject = ActiveCurriculum::findOne(['subjectid' => $subjectid]);
$activesubject = new ActiveSubject();
$activesubject->attributes = $subject->attributes;
$activesubject->isNewRecord = true;
$activesubject->clientid = $clientid;
$activesubject->units = $activesubject->units - 1;
return $activesubject->save();
}
在您的代码中,您从$subject
模型中减去,但保存了$activesubject
模型。