Php Yii 2和x2013;Can';不要使用模型更新

Php Yii 2和x2013;Can';不要使用模型更新,php,yii,yii2,Php,Yii,Yii2,我有一些代码: public function actionEditpost($id) { $post = SiteBlogPosts::find()-> where(["id" => $id])-> asArray()-> one(); $model = new SiteBlogPosts(); $model->id = $post['id']; $model

我有一些代码:

public function actionEditpost($id) {
    $post = SiteBlogPosts::find()->
            where(["id" => $id])->
            asArray()->
            one();

    $model = new SiteBlogPosts();
    $model->id = $post['id'];
    $model->DateCreated = $post['DateCreated'];
    $model->Author = $post['Author'];
    $model->Title = $post['Title'];
    $model->PreviewText = $post['PreviewText'];
    $model->FullTextOfPost = $post['FullTextOfPost'];
    $model->CategoryID = $post['CategoryID'];

    if ($model->load(Yii::$app->request->post())) {

        if ($model->validate()) {

            $model->update();
            print_r($model);
            die;
            return $this->render('AddPostDone', ['model' => $model]);
        }
    } else {
        $cats = SiteBlogCats::find()->where(["CatIsActive" => 1])->asArray()->all();
        return $this->render('EditPost', ['cats' => $cats,
                    "model" => $model,
                    'oldPost' => $post,
        ]);
    }
}
这段代码工作不正确-它不更新MySQL中的记录。 在
/runtime/debug
日志中,我发现了一个有趣的时刻:

为什么使用id为NULL的
而不是id=5的

谢谢大家!

解决方案:

   public function actionEditpost($id) {
        $model = SiteBlogPosts::find()->
                where(["id" => $id])->
                one();

        $cats = SiteBlogCats::find()->where(["CatIsActive" => 1])->asArray()->all();


        if ($model->load(Yii::$app->request->post())) {

            if ($model->validate()) {
                $model->update();
//                print_r($model);
//                die;
                return $this->render('EditPost', ['cats' => $cats,
                            "model" => $model,
                ]);
            }
        } else {
            return $this->render('EditPost', ['cats' => $cats,
                        "model" => $model,
            ]);
        }
    }

Yii2 ActiveRecord默认使用表id作为主键

您不能设置id:

  $model->id = $post['id'];
如果您有其他主键,则可以在SiteBlogPosts模型中使用以下代码,并更改Yi2默认主键列

public static function primaryKey()
{
    return "your_column";
}

您的模型
SiteBlogPosts
的完整内容是什么?尝试将id作为必填字段添加到
rules()
[[['id'],'required'],
  $model->id = $post['id'];
public static function primaryKey()
{
    return "your_column";
}