Yii CRUD数据库操作实例图解

Yii提供了一个gii工具, 它是一个代码生成器工具。它为你提供了CRUD的生成代码。我们将学习如何使用gii生成CRUD。

这里显示了一个简单的示例来生成粗粒。我们将Yii2文件夹命名为crud。我们的表名是雇员。

步骤1打开Gii

在浏览器中, 键入以下内容:http://localhost/crud/frontend/web/index.php?r = gii

YII 2 CRUD1

步骤2产生模型

YII 2 CRUD2

查看上面的快照, 输入表名称(在本例中为employee)。将生成员工模型类。向下滚动页面, 然后单击预览按钮。

YII 2 CRUD3

查看上面的snpashot, 单击”生成”按钮以生成代码。

YII 2 CRUD4

你将看到如上所示的成功消息。


步骤2产生CRUD

YII 2 CRUD5

看一下上面的快照,

在模型类中, 生成路径为frontend \ models \ Employees的雇员文件。

在搜索模型类中, 生成带有路径frontend \ controllers \ EmployeesSearch的EmployeesSearch文件。

在Controller类中, 生成路径为@frontend \ views \ Employees的EmployeesController文件。

单击预览按钮以检查错误。如果没有错误, 请单击”生成”按钮以生成代码。再次, 你将获得成功的消息以进行代码生成。

现在, 我们的CRUD已成功生成。要检查它, 请在浏览器上使用URL http://localhost/crud/frontend/web/index.php?r = employees /

YII 2 CRUD6

查看上面的快照, Employees是我们的表名, 你可以从该表中搜索条目。

要在表中插入值, 请单击创建员工按钮。将出现以下页面。

YII 2 CRUD7

填写上面的详细信息, 然后单击”创建”按钮。数据将被插入到表employees中。

YII 2 CRUD8

查看上面的快照, 我们在表中填写了一些条目。在这里, 你可以看到查看, 更新和删除的图标。

单击”查看”图标时, 将出现包含约翰信息的下一页。

YII 2 CRUD9

单击”更新”图标后, 将出现包含John信息的下一页, 你可以在其中进行任何编辑。进行更改后, 单击更新按钮。

YII 2 CRUD10

单击删除图标后, 将出现以下框, 要求你删除它。

YII 2 CRUD11

生成的代码

在控制器中, 文件EmployeesController.php将具有以下代码。

<?php 

namespace frontend\controllers; 

use Yii; 
use frontend\models\Employees; 
use frontend\models\EmployeesSearch; 
use yii\web\Controller; 
use yii\web\NotFoundHttpException; 
use yii\filters\VerbFilter; 

/** 
 * EmployeesController implements the CRUD actions for Employees model. 
 */ 
class EmployeesController extends Controller 
{ 
    /** 
     * @inheritdoc 
     */ 
    public function behaviors() 
    { 
        return [ 
            'verbs' => [ 
                'class' => VerbFilter::className(), 'actions' => [ 
                    'delete' => ['POST'], ], ], ]; 
    } 

    /** 
     * Lists all Employees models. 
     * @return mixed 
     */ 
    public function actionIndex() 
    { 
        $searchModel = new EmployeesSearch(); 
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams); 

        return $this->render('index', [ 
            'searchModel' => $searchModel, 'dataProvider' => $dataProvider, ]); 
    } 

    /** 
     * Displays a single Employees model. 
     * @param integer $id 
     * @return mixed 
     */ 
    public function actionView($id) 
    { 
        return $this->render('view', [ 
            'model' => $this->findModel($id), ]); 
    } 

    /** 
     * Creates a new Employees model. 
     * If creation is successful, the browser will be redirected to the 'view' page. 
     * @return mixed 
     */ 
    public function actionCreate() 
    { 
        $model = new Employees(); 

        if ($model->load(Yii::$app->request->post()) && $model->save()) { 
            return $this->redirect(['view', 'id' => $model->id]); 
        } else { 
            return $this->render('create', [ 
                'model' => $model, ]); 
        } 
    } 
            
/** 
     * Updates an existing Employees model. 
     * If update is successful, the browser will be redirected to the 'view' page. 
     * @param integer $id 
     * @return mixed 
     */ 
    public function actionUpdate($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('update', [ 
                'model' => $model, ]); 
        } 
    } 

    /** 
     * Deletes an existing Employees model. 
     * If deletion is successful, the browser will be redirected to the 'index' page. 
     * @param integer $id 
     * @return mixed 
     */ 
    public function actionDelete($id) 
    { 
        $this->findModel($id)->delete(); 
 	return $this->redirect(['index']); 
    } 

    /** 
     * Finds the Employees model based on its primary key value. 
     * If the model is not found, a 404 HTTP exception will be thrown. 
     * @param integer $id 
     * @return Employees the loaded model 
     * @throws NotFoundHttpException if the model cannot be found 
     */ 
    protected function findModel($id) 
    { 
        if (($model = Employees::findOne($id)) !== null) { 
            return $model; 
        } else { 
            throw new NotFoundHttpException('The requested page does not exist.'); 
        } 
    } 
}

在模型中, 文件Employees.php将具有以下代码。

<?php 

namespace frontend\models; 

use Yii; 

/** 
 * This is the model class for table "employees". 
 * 
 * @property integer $id 
 * @property string $name 
 * @property string $designation 
 * @property integer $contact 
 * @property string $email 
 */ 
class Employees extends \yii\db\ActiveRecord 
{ 
    /** 
     * @inheritdoc 
     */ 
    public static function tableName() 
    { 
        return 'employees'; 
    } 

    /** 
     * @inheritdoc 
     */ 
    public function rules() 
    { 
        return [ 
            [['name', 'designation', 'contact', 'email'], 'required'], [['contact'], 'integer'], [['name'], 'string', 'max' => 20], [['designation'], 'string', 'max' => 50], [['email'], 'string', 'max' => 80], ]; 
    } 

    /** 
     * @inheritdoc 
     */ 
    public function attributeLabels() 
    { 
        return [ 
            'id' => 'ID', 'name' => 'Name', 'designation' => 'Designation', 'contact' => 'Contact', 'email' => 'Email', ]; 
    } 
}

在模型中, 文件EmployeesSearch.php将具有以下代码。

<?php 

namespace frontend\models; 

use Yii; 
use yii\base\Model; 
use yii\data\ActiveDataProvider; 
use frontend\models\Employees; 

/** 
 * EmployeesSearch represents the model behind the search form about `frontend\models\Employees`. 
 */ 
class EmployeesSearch extends Employees 
{ 
    /** 
     * @inheritdoc 
     */ 
    public function rules() 
    { 
        return [ 
            [['id', 'contact'], 'integer'], [['name', 'designation', 'email'], 'safe'], ]; 
    } 

    /** 
     * @inheritdoc 
     */ 
    public function scenarios() 
    { 
        // bypass scenarios() implementation in the parent class 
        return Model::scenarios(); 
    } 

    /** 
     * Creates data provider instance with search query applied 
     * 
     * @param array $params 
     * 
     * @return ActiveDataProvider 
     */ 
    public function search($params) 
    { 
       $query = Employees::find(); 

        // add conditions that should always apply here 

        $dataProvider = new ActiveDataProvider([ 
            'query' => $query, ]); 

        $this->load($params); 

        if (!$this->validate()) { 
            // uncomment the following line if you do not want to return any 
	records when validation fails 
            // $query->where('0=1'); 
            return $dataProvider; 
        } 

       // grid filtering conditions 
        $query->andFilterWhere([ 
            'id' => $this->id, 'contact' => $this->contact, ]); 

        $query->andFilterWhere(['like', 'name', $this->name]) 
            ->andFilterWhere(['like', 'designation', $this->designation]) 
            ->andFilterWhere(['like', 'email', $this->email]); 

        return $dataProvider; 
      } 
  }

在视图中, 文件view.php将具有以下代码。

<?php 

use yii\helpers\Html; 
use yii\widgets\DetailView; 

/* @var $this yii\web\View */ 
/* @var $model frontend\models\Employees */ 

$this->title = $model->name; 
$this->params['breadcrumbs'][] = ['label' => 'Employees', 'url' => ['index']]; 
$this->params['breadcrumbs'][] = $this->title; 
?> 
<div class="employees-view"> 

    <h1><?= Html::encode($this->title) ?></h1> 

    <p> 
       <?= Html::a('Update', ['update', 'id' => $model->id], ['class' => 'btn btn-primary']) ?> 
        <?= Html::a('Delete', ['delete', 'id' => $model->id], [ 
            'class' => 'btn btn-danger', 'data' => [ 
                'confirm' => 'Are you sure you want to delete this item?', 'method' => 'post', ], ]) ?> 
    </p> 

    <?= DetailView::widget([ 
        'model' => $model, 'attributes' => [ 
            'id', 'name', 'designation', 'contact', 'email:email', ], ]) ?> 

</div>

在视图中, 文件form.php将具有以下代码。

<?php 

use yii\helpers\Html; 
use yii\widgets\ActiveForm; 

/* @var $this yii\web\View */ 
/* @var $model frontend\models\Employees */ 
/* @var $form yii\widgets\ActiveForm */ 
?> 

<div class="employees-form"> 

    <?php $form = ActiveForm::begin(); ?> 

    <?= $form->field($model, 'name')->textInput(['maxlength' => true]) ?> 

    <?= $form->field($model, 'designation')->textInput(['maxlength' => true]) ?> 

    <?= $form->field($model, 'contact')->textInput() ?> 

    <?= $form->field($model, 'email')->textInput(['maxlength' => true]) ?> 

    <div class="form-group"> 
        <?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?> 
   </div> 

    <?php ActiveForm::end(); ?> 

</div>

在视图中, 文件search.php将具有以下代码。

<?php 

use yii\helpers\Html; 
use yii\widgets\ActiveForm; 

/* @var $this yii\web\View */ 
/* @var $model frontend\models\EmployeesSearch */ 
/* @var $form yii\widgets\ActiveForm */ 
?> 

<div class="employees-search"> 

    <?php $form = ActiveForm::begin([ 
        'action' => ['index'], 'method' => 'get', ]); ?> 

    <?= $form->field($model, 'id') ?> 

    <?= $form->field($model, 'name') ?> 

    <?= $form->field($model, 'designation') ?> 

    <?= $form->field($model, 'contact') ?> 

    <?= $form->field($model, 'email') ?> 

    <div class="form-group"> 
        <?= Html::submitButton('Search', ['class' => 'btn btn-primary']) ?> 
       <?= Html::resetButton('Reset', ['class' => 'btn btn-default']) ?> 
    </div> 

    <?php ActiveForm::end(); ?> 

</div>

在视图中, 文件create.php将具有以下代码。

<?php 

use yii\helpers\Html; 


/* @var $this yii\web\View */ 
/* @var $model frontend\models\Employees */ 

$this->title = 'Create Employees'; 
$this->params['breadcrumbs'][] = ['label' => 'Employees', 'url' => ['index']]; 
$this->params['breadcrumbs'][] = $this->title; 
?> 
<div class="employees-create"> 

    <h1><?= Html::encode($this->title) ?></h1> 

    <?= $this->render('_form', [ 
        'model' => $model, ]) ?> 

</div>

在视图中, 文件index.php将具有以下代码。

<?php 

use yii\helpers\Html; 
use yii\grid\GridView; 

/* @var $this yii\web\View */ 
/* @var $searchModel frontend\models\EmployeesSearch */ 
/* @var $dataProvider yii\data\ActiveDataProvider */ 

$this->title = 'Employees'; 
$this->params['breadcrumbs'][] = $this->title; 
?> 
<div class="employees-index"> 

    <h1><?= Html::encode($this->title) ?></h1> 
    <?php // echo $this->render('_search', ['model' => $searchModel]); ?> 

    <p> 
        <?= Html::a('Create Employees', ['create'], ['class' => 'btn btn-success']) ?> 
    </p> 
    <?= GridView::widget([ 
        'dataProvider' => $dataProvider, 'filterModel' => $searchModel, 'columns' => [ 
            ['class' => 'yii\grid\SerialColumn'], 'id', 'name', 'designation', 'contact', 'email:email', ['class' => 'yii\grid\ActionColumn'], ], ]); ?> 
</div>

在视图中, 文件update.php将具有以下代码。

<?php 

use yii\helpers\Html; 

/* @var $this yii\web\View */ 
/* @var $model frontend\models\Employees */ 

$this->title = 'Update Employees: ' . $model->name; 
$this->params['breadcrumbs'][] = ['label' => 'Employees', 'url' => ['index']]; 
$this->params['breadcrumbs'][] = ['label' => $model->name, 'url' => ['view', 'id' => $model->id]]; 
$this->params['breadcrumbs'][] = 'Update'; 
?> 
<div class="employees-update"> 

    <h1><?= Html::encode($this->title) ?></h1> 

    <?= $this->render('_form', [ 
        'model' => $model, ]) ?> 

</div>

下载此示例

微信公众号
手机浏览(小程序)
0
分享到:
没有账号? 忘记密码?