Yii2.0实现增删改查(两表)+搜索分页,文件上传

14 篇文章 0 订阅
4 篇文章 0 订阅

1.感谢幸运的您以这种方式搜到了我,记录熟悉Yii2.0框架,希望对看到的你有帮助哦,喜欢的话点个赞,如果你想快递熟悉了解,可以看看

添加页面  index.php

   <form action="?r=watch/add" method="post" enctype="multipart/form-data">
    
        手表名称  <input type="text" name="wname" id=""><br>
        手表价格 <input type="text" name="wprice" id=""><br>
        手表图片 <input type="file" name="wimg" id=""><br>
            品牌 <select name="bid" id="">
                    <option value="">-请选择品牌-</option>
                    <?php foreach($brand as $v):?>
                        <option value="<?= $v->bid ?>"><?= $v->bname ?></option>
                    <?php endforeach;?>
                </select><br>
        <!-- 必须写的   写了这个才能用写这个表单-->
            <input name="_csrf" type="hidden" value="<?= Yii::$app->request->csrfToken ?>">
            <input type="submit" value="添加">
    </form>

列表展示 show.php 

<?php
// use yii\helpers\Html;
use yii\widgets\LinkPager;
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <!-- 搜索部分开始 -->
    <form action="?r=watch/show" method="get">
        名称:<input type="text" name="wname" value="<?= $wname ?>">
        价格:<input type="text" name="wprice" value="<?= $wprice;?>">
        品牌 <select name="bid">
                    <option value="">-请选择品牌-</option>
                    <?php foreach($brand as $v):?>
                        <option value="<?= $v->bid ?>" <?php if($bid == $v->bid){echo "selected";}?>><?= $v->bname ?></option>
                    <?php endforeach;?>
                </select>
        <input type="hidden" name="r" value="watch/show">
        <input type="submit" value="搜索">
    </form>
    <!-- 搜索部分结束 -->
    <strong style="color:red;">手表列表展示</strong>
    <table>
        <tr>
            <td>ID</td>
            <td>手表名称</td>
            <td>手表价格</td>
            <td>手表图片</td>
            <td>品牌</td>
            <td>操作</td>
        </tr>
        <?php foreach($model as $k=>$v):?>
        <tr>
            <td><?= $v->id ?></td>
            <td><?= $v->wname ?></td>
            <td><?= $v->wprice ?></td>
            <td><img src="/uploads/<?= $v->wimg ?>" alt="手表图片" width="50px" height="50px"></td>
            <td>
                <!-- 品牌这里是数组还需要继续循环 这里和之前你见到的两个表的查询显示品牌名称是不一样的 注意 注意  注意 -->
                <?php foreach($v['brand'] as $kk=>$vv):?>
                    <?= $vv->bname ?>
                <?php endforeach;?>
            </td>
            <td>
                <a href="?r=watch/updates&id=<?= $v->id ?>">编辑</a>||
                <a onclick="return confirm('确定要删除吗?');" href="?r=watch/delete&id=<?= $v->id ?>">删除</a>
            </td>
        </tr>
        <?php endforeach;?>
    </table>
    <?= LinkPager::widget([
        'pagination' => $pages,
        'nextPageLabel' => '下一页', 
        'prevPageLabel' => '上一页',
        'firstPageLabel' => '首页', 
        'lastPageLabel' => '尾页', 
        ]) ?>
    <a href="?r=watch/index">添加</a>
</body>
</html>

修改页面

<form action="?r=watch/updates" method="post" enctype="multipart/form-data">
        <input type="hidden" name="id" value="<?= $info->id ?>">
        手表名称  <input type="text" name="wname" value="<?php echo $info['wname'];?>"><br>
        手表价格 <input type="text" name="wprice" value="<?php echo $info['wprice'];?>"><br>
        手表图片 <input type="file" name="wimg"><img src="\uploads\<?= $info->wimg ?>" width="80px" height="80px" alt=""><br>
        品牌    <select name="bid" id="">
                    <option value="">-请选择品牌-</option>
                    <?php foreach($brand as $v):?>
                        <option value="<?= $v->bid ?>" <?php if($info['bid'] == $v->bid){ echo 'selected';}?>><?= $v->bname ?></option>
                    <?php endforeach;?>
                </select><br>
            <input type="hidden" name="_csrf" value="<?= Yii::$app->request->csrfToken ?>">
            <input type="submit" value="修改">
</form>

2.接下来是模型文件

<?php

namespace app\models;

use Yii;
use yii\web\UploadedFile;
use yii\base\Model;
/**
 * This is the model class for table "country".
 *
 * @property string $code
 * @property string $name
 * @property int $population
 */
class Watch extends \yii\db\ActiveRecord
{
    /**
     * {@inheritdoc}
     */
    public static function tableName()
    {
        return 'watch';
    }
    //关联表 get(关联表Model名)
    public function getBrand(){
        //参数
        return $this->hasMany(Brand::className(),['bid'=>'bid']);
    }
    public function rules(){
        return [
            ['wname','string','message'=>'手表名称不能为空'],
            ['wprice','string','message'=>'手表价格不能为空'],
            ['wimg','file', 'maxFiles' => 10],
        ];
    }
    /**
     * {@inheritdoc}
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'wname' => Yii::t('app','手表名称'),
            'wprice' => Yii::t('app','手表价格'),
            'wimg' => Yii::t('app', '手表图片'),
        ];
    }
}

品牌模型 Brand.php

<?php
namespace app\models;
use Yii;
// 模板继承的下面这个是为了数据库操作
use yii\db\ActiveRecord;
/**
 * This is the model class for table "country".
 *
 * @property string $code
 * @property string $name
 * @property int $population
 */
class Brand extends ActiveRecord
{
    /**
     * {@inheritdoc}
     */
    public static function tableName()
    {
        return 'brand';
    }
    public function rules(){
        return [
            ['bname','string','message'=>'品牌名称不能为空'],
        ];
    }
    /**
     * {@inheritdoc}
     */
    public function attributeLabels()
    {
        return [
            'bid' => '品牌id',
            'bname' => Yii::t('app','品牌名称'),
        ];
    }
}

3.控制器文件

<?php

namespace app\controllers;

use Yii;
use yii\data\Pagination;
use app\models\Watch;
use app\models\Brand;
use yii\web\Controller;
use yii\web\UploadedFile;
class WatchController extends Controller
{
    public $enableCsrfValidation = false;
    /**
     * @inheritDoc
     */
    public function actionIndex()
    {
        //实例化对象 获取品牌表所有的数据
        $model = Brand::find();
        $brand = $model->all(); 
        return $this->render('index',["brand"=>$brand]);
    }
    /** 
     * 添加 
     */
    public function actionAdd(){
        // print_r(Yii::$app->request->post('wname'));die;
        $watch = new Watch;
        //接收表单以post方式传输过来的数据 最上方要引入Yii
        $watch['wname'] = Yii::$app->request->post('wname'); 
        $watch['wprice'] = Yii::$app->request->post('wprice');
        $watch['bid'] = Yii::$app->request->post('bid');
        $watch['wtime'] = date("Y-m-d h:i:s",time()); 
        //文件处理 
        //接收上传的文件数组
        $image=UploadedFile::getInstanceByName('wimg');
         //路径           文件的临时位置
         $path = Yii::$app->basePath.'\web\uploads\\';
         //图片的名                名字                       后缀
         $filename = md5($image->getBaseName()).'.'.$image->getExtension();
         //移动文件          路径+文件名=要移动的位置
         $image->saveAs($path.$filename);
         $watch['wimg'] = $filename;
        $res = $watch->save();
        //返回bool true表示添加成功
        if($res){
            Yii::$app->session->setFlash('success', '添加成功!');
            $this->redirect(array('watch/show'));
        }else{
            Yii::$app->session->setFlash('error', '添加失败!');
            $this->redirect(array('watch/index'));
        }
    }
    //列表展示
    public function actionShow(){
        //实例化 
        $query = Watch::find();
        //接收搜索的关键字
        $wname = Yii::$app->request->get('wname');
        $wprice = Yii::$app->request->get('wprice');
        $bid = Yii::$app->request->get('bid');
        //搜索where条件拼接
        $where = 1;
        if(!empty($wname)){
            $where .= " and wname like '%$wname%'";
        }
        if(!empty($wprice)){
            $where .= " and wprice like '%$wprice%'";
        }
        if(!empty($bid)){
            // 一定要在这里写指的是哪个表中的id,否则报错
            //这里要写成'',否则报错,和上面的名称是有区别的
            $where .= ' and watch.bid='.$bid.'';
        }
        $pages = new Pagination([
            'defaultPageSize' => '4',
            //分页中增加搜索的条件 
            'totalCount' => $query->where($where)
                                  ->count(),
        ]);
        $model = $query->orderBy('id DESC')
        //关联表名
        ->joinWith(['brand'])
        //模糊查询
        ->where($where)
        ->offset($pages->offset)
        ->limit($pages->limit)
        ->all();
        // print_r($model);die;
         //实例化对象 获取品牌表所有的数据 将搜索的下拉菜单数据变活
         $model1 = Brand::find();
         $brand = $model1->all(); 
        return $this->render('show', [
            'model' => $model,
            'pages' => $pages,
            // 实现搜索的保留条件
            'wname' =>$wname,
            'wprice' =>$wprice,
            'bid' =>$bid,
            // 渲染数据到搜索的下拉菜单
            'brand' =>$brand,
        ]);
    }
    //删除  
    public function actionDelete(){
        $id = \Yii::$app->getRequest()->get('id');
        $model = Watch::findOne($id);
        $res = $model->delete();
        if($res){
            Yii::$app->session->setFlash('success', '删除成功!');
            $this->redirect(array('watch/show'));
        }else{
            Yii::$app->session->setFlash('error', '删除失败!');
            $this->redirect(array('watch/show'));
        }
    }
    //修改
    public function actionUpdates(){
        // 实例化对象  接收id值 
        $postData = Yii::$app->request->post('id');
        if(!$postData){
            // 接收id值  以下写法是获取网址中某一个参数的值  
            $id =Yii::$app->request->get('id');
            $info = Watch::findOne($id);

            //查询品牌表中的数据 展示修改表单中的下拉菜单
            $model1 = Brand::find();
            $brand = $model1->all(); 
            return $this->render('update',['info'=>$info,'brand'=>$brand]);
        }else{
            //实例化对象
            $model = new Watch();
            //接收所有的数据
            $data = Yii::$app->request->post();
            //移除_csrf参数 因为他不需要入库
            unset($data['_csrf']);

            //接收上传的文件数组
            $image=UploadedFile::getInstanceByName('wimg');
            //路径           文件的临时位置
            $path = Yii::$app->basePath.'\web\uploads\\';
            //图片的名                名字                       后缀
            $filename = md5($image->getBaseName()).'.'.$image->getExtension();
            //移动文件          路径+文件名=要移动的位置
            $image->saveAs($path.$filename);

            //获取id  
            $id = $data['id'];
            $data['wimg'] = $filename;
            //写修改的sql语句
            $res = $model->updateAll($data,"id=$id");
            // var_dump($res);die;
                 //var_dump($res);//返回 int 1表示修改成功  int 0表示未做修改  
            if($res==1){
                Yii::$app->session->setFlash('success', '修改成功!');
                $this->redirect(array('watch/show'));
            }else if($res==0){
                Yii::$app->session->setFlash('error', '数据未做任何修改!!!');
                $this->redirect(array('watch/show'));
            }else{
                Yii::$app->session->setFlash('error', '修改失败!');
                $this->redirect(array('watch/edit',['id',$id]));
            }
        }
    }
}
?>

4.效果

 

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

大帅同学

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值