yii2.0增删改查实例讲解

yii2.0增删改查实例讲解
一.创建数据库文件.

创建表
CREATE TABLE `resource` (
  `id` int(10) NOT NULL AUTO_INCREMENT,
  `texture` varchar(50) NOT NULL COMMENT '材质',
  `mark` varchar(50) NOT NULL COMMENT '牌号',
  `manufacturers` varchar(100) NOT NULL COMMENT '厂家',
  `price` int(11) NOT NULL COMMENT '价格',
  PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=10 DEFAULT CHARSET=utf8;

INSERT INTO `resource` VALUES ('1', 'PP', '300H', '中沙石化', '8300');
INSERT INTO `resource` VALUES ('2', 'LDPE', 'LD605', '燕山石化', '9850');
INSERT INTO `resource` VALUES ('3', 'ABS', 'D-190 ', '镇江奇美', '11300');
INSERT INTO `resource` VALUES ('4', 'ABS', 'D-180 ', '镇江奇美', '11500');
INSERT INTO `resource` VALUES ('5', 'ABS', 'D-2400 ', '镇江奇美', '17600');
INSERT INTO `resource` VALUES ('6', 'YH', 'YH100', '测试', '199466');
INSERT INTO `resource` VALUES ('7', 'YH', 'YH200', '测试', '56256');
INSERT INTO `resource` VALUES ('8', 'QW', 'QW-21', '压紧', '19865');
INSERT INTO `resource` VALUES ('9', 'ZX', 'ZX-82', '水果', '98632');
INSERT INTO `resource` VALUES ('10', 'OP', 'OP98', '叶城', '38941');

 
二.定义控制器controller

namespace app\controllers;

use Yii;
use yii\web\Controller;
use yii\data\Pagination;
use app\models\Resources;

class ResourcesController extends Controller
{
    /**
     * 数据列表
     */
    public function actionIndex($id = '')
    {
        $query = Resources::find();
        $pages = new Pagination([
            'defaultPageSize' => '4',
            'totalCount' => $query->count(),
        ]);

        $model = $query->orderBy('id DESC')
        ->offset($pages->offset)
        ->limit($pages->limit)
        ->all();

        return $this->render('index', [
            'model' => $model,
            'pages' => $pages,
            'id' => $id,
        ]);
    }

    /**
     * 添加数据
     */
    public function actionAdd($id = '')
    {
        if($id){
            $model = Resources::findOne($id);
        }else{
            $model = new Resources();
        }
        if($model->load(Yii::$app->request->post()) && $model->validate()){
            $model->save();
            return $this->redirect(array('resources/index'));
        }
        return $this->render('add', [
            'model' => $model,
            'id' => $id,
        ]);
    }

     /**
     * 更新数据
     */
    public function actionUpdate($id)
    {
        return $this->redirect(array('resources/add','id' => $id));
    }

    /**
     * 删除数据
     */
    public function actionDelete($id)
    {
        Resources::findOne($id)->delete();
        return $this->redirect(array('resources/index'));
    }
}

三.定义model

namespace app\models;

use Yii;

/**
 * This is the model class for table "resource".
 *
 * @property integer $id
 * @property string $texture
 * @property string $mark
 * @property string $manufacturers
 * @property integer $price
 */
class Resources extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'resource';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['texture', 'mark', 'manufacturers', 'price'], 'required'],
            [['price'], 'integer'],
            [['texture', 'mark'], 'string', 'max' => 50],
            [['manufacturers'], 'string', 'max' => 100],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => "ID",
            'texture' =>"材质",
            'mark' => Yii::t('app', '牌号'),
            'manufacturers' => Yii::t('app', '厂家'),
            'price' => Yii::t('app', '价格'),
        ];
    }
}

四.定义视图view
1.index.php

<?php
use yii\helpers\Html;
use yii\widgets\LinkPager;
?>
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>资源列表</title>
    <style type="text/css">
        .list-head{margin-bottom:10px;overflow:hidden;}
        .list-head strong{padding:6px 0;font-size:16px;}

        .list-table{width:100%;}
        .list-table thead{font-weight:bold;}
        .list-table td{line-height:30px;text-align:center;border:1px solid #eee;}

        .fl{float:left;}
        .fr{float:right;}
    </style>
</head>
<body>
<?= $id ?>
<div class="list-head">
    <strong class="fl">资源列表</strong>
    <a href="index.php?r=resources/add" class="btn btn-primary fr">添加</a>
</div>
<table class="list-table">
    <thead>
    <tr>
        <td>ID</td>
        <td>材质</td>
        <td>牌号</td>
        <td>厂家</td>
        <td>价格</td>
        <td>操作</td>
    </tr>
    </thead>
    <tbody>
    <?php foreach($model as $resource): ?>
        <tr>
            <td><?= Html::encode($resource->id) ?></td>
            <td><?= Html::encode($resource->texture) ?></td>
            <td><?= Html::encode($resource->mark) ?></td>
            <td><?= Html::encode($resource->manufacturers) ?></td>
            <td><?= Html::encode($resource->price) ?></td>
            <td>
                <a href="index.php?r=resources/update&id=<?= Html::encode($resource->id) ?>">编辑</a>
                <a href="index.php?r=resources/delete&id=<?= Html::encode($resource->id) ?>" οnclick="if(confirm('确定删除该条数据?')==false)return false;">删除</a>
            </td>
        </tr>
    <?php endforeach; ?>
    </tbody>
</table>
<?= LinkPager::widget(['pagination' => $pages]) ?>
</body>
</html>

2.add.php

<?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;
?>

<?php $form = ActiveForm::begin(); ?>
<?php if($id): ?>
    <?= $form->field($model, 'id')->textInput(['value' => $id, 'disabled' => 'disabled']) ?>
<?php endif;  ?>
<?= $form->field($model, 'texture') ?>
<?= $form->field($model, 'mark') ?>
<?= $form->field($model, 'manufacturers') ?>
<?= $form->field($model, 'price') ?>
    <div class="form-group">
        <?php if($id): ?>
            <?= Html::submitButton('修改', ['class' => 'btn btn-primary']) ?>
        <?php else:?>
            <?= Html::submitButton('添加', ['class' => 'btn btn-primary']) ?>
        <?php endif;  ?>
    </div>
<?php ActiveForm::end(); ?>

五.运行结果如下:

转载于:https://www.cnblogs.com/wangjinke/p/5836937.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值