Yii 2.0 - 输入值在数据库中保存为 null
Yii 2.0 - Input values saved as null in database
在我的练习应用程序中,我有一个名为 'music' 的 table,它包含 3 列 - id、title 和 artist。每当我尝试将表单中的输入值插入数据库时,都会添加一条新记录,但只有 id 有一个值,title 和 artist 都是空的。下面是我的模型:
<?php namespace app\models;
/**
* This is the model class for table "music".
*
* @property integer $id
* @property string $title
* @property string $artist
*/
class MusicEntry extends \yii\db\ActiveRecord {
public $title;
public $artist;
public $id;
public static function tableName() {
return 'music';
}
public function rules() {
return [
[['title', 'artist'], 'required'],
[['id'], 'safe'],
];
}
} ?>
虽然我的控制器操作看起来像这样:
public function actionMusicEntry() {
$model = new MusicEntry ();
if (isset ( $_POST ['MusicEntry'] )) {
$model->load($_POST);
if ($model->save()) {
Yii::$app->session->setFlash ( 'success', 'Model has been saved' );
$this->redirect ( [
'music-entry',
'id' => $model->id
] );
}
}
return $this->render ( 'music-entry', [
'model' => $model
] );
}
我尝试在使用 $_POST 加载模型后获取艺术家和标题的值,它具有我在表单中输入的值。鉴于此,为什么输入值在数据库中保存为空值?
进一步调整后,我在模型中找到了问题的原因。我不得不删除 $artist 和 $title 的声明。我仍然不确定为什么添加这些变量会导致这样的问题。还在研究中。
在我的练习应用程序中,我有一个名为 'music' 的 table,它包含 3 列 - id、title 和 artist。每当我尝试将表单中的输入值插入数据库时,都会添加一条新记录,但只有 id 有一个值,title 和 artist 都是空的。下面是我的模型:
<?php namespace app\models;
/**
* This is the model class for table "music".
*
* @property integer $id
* @property string $title
* @property string $artist
*/
class MusicEntry extends \yii\db\ActiveRecord {
public $title;
public $artist;
public $id;
public static function tableName() {
return 'music';
}
public function rules() {
return [
[['title', 'artist'], 'required'],
[['id'], 'safe'],
];
}
} ?>
虽然我的控制器操作看起来像这样:
public function actionMusicEntry() {
$model = new MusicEntry ();
if (isset ( $_POST ['MusicEntry'] )) {
$model->load($_POST);
if ($model->save()) {
Yii::$app->session->setFlash ( 'success', 'Model has been saved' );
$this->redirect ( [
'music-entry',
'id' => $model->id
] );
}
}
return $this->render ( 'music-entry', [
'model' => $model
] );
}
我尝试在使用 $_POST 加载模型后获取艺术家和标题的值,它具有我在表单中输入的值。鉴于此,为什么输入值在数据库中保存为空值?
进一步调整后,我在模型中找到了问题的原因。我不得不删除 $artist 和 $title 的声明。我仍然不确定为什么添加这些变量会导致这样的问题。还在研究中。