为什么数据不能保存?
问题描述:
我想处理表单并从表单保存数据做我的分贝。 我想在保存之前从表单和另一个数据获取一些数据(如当前user_id,当前日期时间)。我创建方法控制器:为什么数据不能保存?
public function actionCreate()
{
$model = new Post();
if ($model->load(\Yii::$app->request->post()) && $model->validate()) {
$model->user_id = \Yii::$app->user->getId();
$model->created_at = \Yii::$app->formatter->asDate(new \DateTime(),'php:Y-m-d');
$model->image = UploadedFile::getInstance($model, 'image');
if($model->upload()) {
$model->image = ('web/images/' . $model->image->baseName . '.' . $model->image->extension);
} else {
$model->image = 0;
}
$model->save();
return $this->redirect(['site/blog']);
} else {
return $this->render('blog/create', ['model' => $model]);
}
}
和我的Post模型:
class Post extends ActiveRecord
{
public $title;
public $text;
public $image;
public $comments;
public function rules()
{
return [
[['title', 'text'], 'required'],
[['image'], 'file', 'extensions' => 'png, jpg'],
];
}
public function upload()
{
if ($this->image->saveAs(\Yii::getAlias('@app') .'\web\images\\' . $this->image->baseName . '.' . $this->image->extension))
return true;
else {
return false;
}
}
public function getUser()
{
return $this->hasOne(User::className(),['id' => 'user_id']);
}
}
但现在当我把我的表格只有USER_ID,created_at,保存在我的分贝。我做错了什么?
这可能是因为'$ model-> image = 0',这可能是上传造成'false'响应的原因.. –
如果'$ model-> save();'失败,则应该将视图渲染为看你的表单中的错误('return $ this-> render('blog/create',['model'=> $ model]);') – gmc
你应该启用错误报告和/或检查你的日志文件追查问题。也许是路径中的双斜线导致文件上传失败,即“\ web \ images \\”?你也可以考虑使用正斜杠。您还应该确保Web服务器可以写入'web \ images'文件夹。 – Cyclonecode