是否有一种方法可以在int列中减去一个值来表示1?我有一个按钮,当它被点击时,它会调用一个函数来保存表中的数据,但我想知道如何使用yii 2减去数据库中的数字,我已经尝试了下面的代码,但它没有效果。有人能教我怎么用yii做数学运算吗?
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]);
}
当你在AR对象中做了一些更改并希望保存这些更改时,你应该执行->save()
:
$subject->units = $subject->units - 1;
$subject->save();
看起来你只是忘记了。
您可以使用以下命令大量复制属性,然后保存新模型:
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
模型。