如果数量不存在,尝试设置默认数量


Trying to set a default quantity, if no quantity exists

如果我的数据库中没有现有的令牌数量,我要做的是将令牌数量设置为0。然而,我下面的代码不能工作,尽管它与我用来完美工作的buy和spend函数几乎相同。

public function actionIndex() {
    $_id = Yii::app()->user->getId();
    $model = Tokens::model()->findByAttributes(array('UserID' => $_id));
    if ($model === null)
        $defaultqty = 0;
        $model->TokenAmount = ($model->TokenAmount + $defaultqty);
        $model->save(false);
        throw new CHttpException(404, "yea it's broke, deal with it");
    $this->render('index', array(
        'model' => $model,
    ));
}
$model = Tokens::model()->findByAttributes(array('UserID' => $_id));
    if ($model === null) ...

如果$model变量中没有模型对象。你应该在使用它之前创建一个新模型。

$model = Tokens::model()->findByAttributes(array('UserID' => $_id));
    if ($model === null) {
        $model = new Tokens;
        ...

我认为最好使用CActiveRecord beforeSave()方法

class Tokens extends MyActiveModel {
    private $defaultTokenAmount = 0;
    ...
    public function beforeSave() {
        if (empty($this->TokenAmount)) {
            $this->TokenAmount = $defaultTokenAmount;
        }
        return parent::beforeSave();
    }
}