Yii2 ActiveRecord模型最佳实践


Yii2 ActiveRecord Model best practice

我有这些类:

型号:

namespace app'models;
use 'yii'db'ActiveRecord;
class MyModel extends ActiveRecord {
public function rules() {
    return [
        [['name'], 'required'],
        [['id'], 'default', 'value' => null]
    ];
}
}

控制器:

<?php
namespace app'controllers;
use Yii;
use yii'web'Controller;
use app'models'MyModel;
class MymodelController extends Controller{
    public function actionEdit($id = null){
        $model = new MyModel();
        if ($model->load(Yii::$app->request->post()) && $model->validate() && $model->save()) {
            Yii::$app->session->setFlash('msg', 'Model has been saved with ID ' . $model->id);
        }
        return $this->render('edit', [
           'model' => $model 
        ]);
    }
}

视图:

<?php 
use yii'helpers'Html;
use yii'widgets'ActiveForm;
?>
<?php if(Yii::$app->session->hasFlash('msg')): ?>
    <div class="alert alert-success"><?= Yii::$app->session->getFlash('msg'); ?></div>
<?php endif; ?>
<?php $form = ActiveForm::begin(); ?>
<?= Html::activeHiddenInput($model, 'id');  ?>
<?= $form->field($model, 'name') ?>
<?= Html::submitButton('Submit', ['class' => 'btn btn-primary']) ?>
<?php ActiveForm::end(); ?>

我想使用此视图进行编辑和插入。编辑无法正常工作,因为我正在创建一个新对象,而不是更改控制器中的现有对象。我不确定这里的最佳实践是什么,或者我是否缺少一些已经存在的内置功能?

  • 我是否应该创建自己的模型类并实现逻辑模型<->控制器中的活动记录

  • 我是否应该在控制器中使用$model->id重新查询数据库,并在需要时复制所有属性

您应该使用两个操作来编辑和插入

对于编辑,首先找到型号

$model = $this->findModel($id);
if ($model->load(Yii::$app->request->post()) && $model->save()) {
        return $this->redirect(['view', 'id' => $model->id]);
    } else {
        return $this->render('edit', [
            'model' => $model,
        ]);
    }
 protected function findModel($id)
    {
        if (($model = MyModel::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }

如果使用CRUD生成控制器,则不必编写这些操作。

对于CRUD(创建、读取/查看、更新和删除),您可以使用gii。这个强大的工具会自动生成ActiveRecord、具有基本操作(索引、查看、创建、更新、删除、查找)的控制器和相关视图所需的所有内容。

在gii中,您首先生成模型类,然后为该类生成CRUD。

但最重要的是,所有这些信息都是相互关联的

看到这个文档非常有用,Yii2的最佳实践已经在工具中列出http://www.yiiframework.com/doc-2.0/guide-start-gii.html

在创建操作中:

public function actionCreate()
{
    $model = new Yourmodel();
    if ($model->load(Yii::$app->request->post())) {
        if($model->save()){
            return $this->redirect(['view']);
        }
    }
    return $this->render('create', [
        'model' => $model,
    ]);
}

在您的更新操作中:

public function actionUpdate($id)
{
    $model = $this->findModel($id);
    if ($model->load(Yii::$app->request->post())) {
        if($model->save()){
            return $this->redirect(['view', 'id' => $model->id]);
        }
    } 
    return $this->render('update', [
        'model' => $model,
    ]);
}