如何将文件名保存到数据库?

时间:2019-04-14 05:59:43

标签: yii yii2

上传照片时出现错误,我想将文件名添加到数据库(到$model->photo_url):

SQLSTATE[HY000]: General error: 1364 Field 'photo_url' doesn't have a default value

我尝试在$filename之后将$photo_url分配给saveAs(),但不起作用。

控制器:

public function actionCreate() {
    $model = new Doctors();
    if ($model->load(Yii::$app->request->post())) {
        $model->image = \yii\web\UploadedFile::getInstance($model, 'image');

        if ($model->save()) {
              $model->uploadPhoto();
            $model->photo_url = $model->fileName;               
            $this->saveSpecialities($model);               
        }
        return $this->redirect(['view', 'id' => $model->id]);
    }
    return $this->render('create', [
                'model' => $model
    ]);
}

//
protected function saveSpecialities($model) {
    foreach ($model->specialites as $var) {
        $speciality = new DoctorsSpeciality();
        $speciality->speciality_id = $var->id;
        $speciality->doctor_id = $model->id;
        $speciality->save();
    }
}

型号

public function uploadPhoto() {
    if ($this->validate()) {
        $this->fileName = $this->generateSlug() . '.' . $this->image->extension;            
        $this->image->saveAs($this->path . $this->fileName);
        Image::thumbnail($this->path . $this->fileName, 200, 200)->save($this->path_middle . $this->fileName, ['quality' => 100]);
        Image::thumbnail($this->path . $this->fileName, 100, 100)->save($this->path_small . $this->fileName, ['quality' => 100]);
        return true;
    } else {
        return false;
    }
}

protected function generateSlug() {
    return Inflector::slug($this->lastname . '-' . $this->middlename . '-' . $this->firstname . '-' . $this->title);
}

所有文件都已正确保存到文件夹,但是如何将$this->fileName保存到$this->photoUrl

P.S。当我尝试在模型中进行$this->photo_url = $this->fileName;时,会收到关于默认值的相同错误。

2 个答案:

答案 0 :(得分:0)

您需要先设置字段,然后再尝试保存模型:

-- Identify the home team as Bayern Munich, Schalke 04, or neither
SELECT 
    CASE WHEN hometeam_id = 10189 THEN 'FC Schalke 04'
        WHEN hometeam_id = 9823 THEN 'FC Bayern Munich'
         ELSE 'Other' END AS home_team,
    COUNT(id) AS total_matches
FROM matches_germany
-- Group by the CASE statement alias
GROUP BY home_team;

然后在if ($model->uploadPhoto() && $model->save()) { $this->saveSpecialities($model); } 内设置photo_url

uploadPhoto()

答案 1 :(得分:-1)

为此(SQLSTATE [HY000]:一般错误:1364字段“ photo_url”没有默认值)

解决方案: 为Created_By设置默认值(例如,空VARCHAR),触发器将始终更新该值。