【问题标题】:How to solve problem when inserting data in database, Yii2?Yii2在数据库中插入数据时如何解决问题?
【发布时间】:2020-10-14 18:07:21
【问题描述】:

我无法在数据库中插入数据。我正在使用 yii2 高级版。

我有 3 个表:默认用户表、帖子和类别。每个帖子都有一个类别,一个类别可以有多个帖子。 但是当我在我的创建表单中单击“保存”时 - 没有任何反应,页面只是刷新。 post 表仍然是空的。

这里是 PostController

    namespace frontend\controllers;

    use Yii;
    use yii\web\Controller;
    use frontend\models\CreateForm;
    use frontend\models\Category;
    use yii\helpers\ArrayHelper;


    class PostController extends Controller
    {
public function actionCreate()
{
    if(Yii::$app->user->isGuest)
    {
        return $this->redirect(['/site/login']);

    }

    $model = new CreateForm();
    $category = Category::find()->all();
    $items = ArrayHelper::map($category, 'id', 'name');
    if ($model->load(Yii::$app->request->post()))
    {
        if ($model->save())
        {
            Yii::$app->session->setFlash(
                'success',
                true

            );
            return $this->refresh();
        } else
            {
                Yii::$app->session->setFlash(
                    'success',
                    false
                );
            }

    }
    return $this->render('create', [
        'model' => $model,
        'items' => $items
    ]);



}

这是 CreateForm 模型

    namespace frontend\models;

    use yii\base\Model;
    use frontend\models\Post;
    use Yii;


    class CreateForm extends Model
    {
        public $category;
        public $title;
        public $content;

public function attributeLabels()
{
    return [
        'category' => 'Category',
        'title' => 'Title',
        'content' => 'Content',
    ];

}

public function save()
{
    $post = new Post();
    $post->user_id = Yii::$app->user->id;
    $post->category_id = $this->category;
    $post->title = $this->title;
    $post->content = $this->content;
    $post->created_at = time();


}

   }

这就是风景

    use yii\bootstrap\ActiveForm;
    use yii\bootstrap\Html;

    $form = ActiveForm::begin();
    echo $form->field($model, 'category')->dropDownList($items);
    echo $form->field($model, 'title')->textInput();
    echo $form->field($model, 'content')->textInput();
    echo Html::submitButton('Save', ['class' => 'btn btn-primary']);
    ActiveForm::end();

我做错了什么,我无法理解

【问题讨论】:

  • 您在CreateForm 中的方法save 不会保存新帖子,只是分配值。您还可以在CreateForm 中添加验证规则。阅读指南中的Creating FormsValidating Input
  • 您使用的是Gii吗? Gii 可以生成你想要的。但不使用 yii\base\Model

标签: php database yii2


【解决方案1】:

好的。我所要做的就是在 CreateForm 的保存方法末尾添加 $post->save()

【讨论】:

    猜你喜欢
    • 2019-09-20
    • 1970-01-01
    • 1970-01-01
    • 2021-05-06
    • 1970-01-01
    • 2021-05-02
    • 1970-01-01
    • 1970-01-01
    • 2021-10-15
    相关资源
    最近更新 更多