YII 1中的getPrimaryKey函数不起作用

时间:2015-03-19 12:34:26

标签: php yii

如何通过YII 1中的getPrimaryKey()获取最后插入的ID?

我的记录已插入数据库,但它返回空值。

我使用了以下代码。

public function saveSurvey($model){ 
    if($model->ID == ''){
        $model->Name = trim($model->Name);
        $model->EngagementQuestionNo = trim($model->EngagementQuestionNo);
        $model->CSVColumnCount = trim($model->CSVColumnCount);
        $model->LocationQuestionNo = trim($model->LocationQuestionNo);
        $model->CreatedOn = new CDbExpression('NOW()');         
        if($model->save()){
            echo 'saved id >> ';
            echo $surveyID  = $model->ID;
        }
        else{
            echo 'error';
        }
   }
}

我目前在模型中的规则

public function rules()
{       
    return array(
        array('Name,EngagementQuestionNo,CSVColumnCount,LocationQuestionNo', 'required'),
        array('CSVColumnCount', 'numerical', 'integerOnly'=>true),
        array('Name', 'length', 'max'=>100),
        array('QuestionNumbers, ID', 'safe'),
        array('ID, Name, CreatedOn, LastModifiedOn,QuestionNumbers', 'safe', 'on'=>'search'),
    );
}

1 个答案:

答案 0 :(得分:1)

您必须初始化Survey模型类的新对象

$ newObjectModel = new Survey();

添加新对象后,您的代码如下所示:

    public function saveSurvey($model){ 
    if($model->ID == ''){
        $newObjectModel = new Survey(); 
        $newObjectModel ->Name = trim($model->Name);
        $newObjectModel ->EngagementQuestionNo = trim($model->EngagementQuestionNo);
        $newObjectModel ->CSVColumnCount = trim($model->CSVColumnCount);
        $newObjectModel ->LocationQuestionNo = trim($model->LocationQuestionNo);
        $newObjectModel ->CreatedOn = new CDbExpression('NOW()');         
        if($newObjectModel ->save()){
            echo $surveyID  = $newObjectModel ->ID;
        }
        else{
            echo 'error';
        }
   }
}