Yii 如何将文件名保存到数据库?
上传照片时,我想将文件名添加到数据库(到Yii 如何将文件名保存到数据库?,yii,yii2,Yii,Yii2,上传照片时,我想将文件名添加到数据库(到$model->photo\u url),但出现错误: SQLSTATE[HY000]: General error: 1364 Field 'photo_url' doesn't have a default value 我试图在saveAs()之后将$filename分配给$photo\u url,但不起作用 控制器: public function actionCreate() { $model = new Doctors(); i
$model->photo\u url
),但出现错误:
SQLSTATE[HY000]: General error: 1364 Field 'photo_url' doesn't have a default value
我试图在saveAs()
之后将$filename
分配给$photo\u url
,但不起作用
控制器:
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();
}
}
模型
所有文件都正确保存到文件夹中,但如何将$this->fileName
保存到$this->photoUrl
另外,当我尝试做$this->photo\u url=$this->fileName
在模型中,我得到了关于默认值的相同错误。对此(SQLSTATE[HY000]:一般错误:1364字段“photo\u url”没有默认值)
解决方案:
为Created_By(例如:empty VARCHAR)设置默认值,触发器将以任何方式更新该值。在尝试保存模型之前,您需要设置字段:
if ($model->uploadPhoto() && $model->save()) {
$this->saveSpecialities($model);
}
然后在uploadPhoto()
的内部设置photo\u url
:
if ($model->uploadPhoto() && $model->save()) {
$this->saveSpecialities($model);
}
public function uploadPhoto() {
if ($this->validate()) {
$this->fileName = $this->generateSlug() . '.' . $this->image->extension;
$this->photo_url = $this->fileName;
$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;
}
}