产品模块相关代码

Original 2019-05-14 12:20:18 219
abstract:<?php /**  * Created by PhpStorm.  * User: Administrator  * Date: 2019/5/14  * Time: 11:22  */ namespace app\admin\control
<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/5/14
 * Time: 11:22
 */
namespace app\admin\controller;
use app\admin\controller\Common;
use app\admin\model\ProductModel;
use think\facade\Request;
use think\facade\Session;


class  Product extends Common{

    public function index(){
        $product = new ProductModel();
        $products = $product->order('id','desc')->paginate(5);
        $this->view->products = $products;

        return $this->fetch();
    }

    public function add(){

        return $this->fetch();
    }

    public function edit(){
        $proId = Request::param('id');
        $product = ProductModel::get($proId);
        $this->view->product = $product;
        // 渲染产品修改界面
        return $this->fetch();
    }

    public function DoAdd(){
        $data = Request::param();
        $title = $data['title'];
        $info = ProductModel::where('title',$title)->find();
        if($info == true){
            return ['res'=>0,'msg'=>'产品标题重复~'];
        }

        $data['time']=time();
        $data['username']=Session::get('username');
        $product = new ProductModel();
        if($product->save($data)){
            return ['res'=>1,'msg'=>'产品添加成功~'];
        }else{
            return ['res'=>0,'msg'=>'发布失败~'];
        }
    }

    public function upload(){
        // 获取上传图片信息
        $file = Request::file('img');
        // 验证图片信息并移动到指定目录
        if ($info = $file->validate(['ext' => 'jpg,jpeg,png,gif'])->move('upload')) {
            // 返回成功的提示信息
            return json(['errno' => 0, 'data' => ['/upload/' . $info->getSaveName()]]);
        } else {
            // 返回失败的提示信息
            return $file->getError();
        }

    }

    public function DoEdit()
    {
        // 获取提交过来的数据
        $data = Request::param();
        $product = new ProductModel();
        $data['time'] = time();
        $data['username'] = Session::get('username');
        $info = $product->save([
            'title' => $data['title'],
            'desc' => $data['desc'],
            'content' => $data['content'],
            'price' => $data['price'],
            'time' => $data['time'],
            'username' => $data['username'],
        ], ['id' => $data['id']]);
        if ($info) {
            return ['res' => 1, 'msg' => '更新成功!'];
        } else {
            return ['res' => 0, 'msg' => '更新失败!'];
        }
    }

    public function del(){

        // 获取需要删除的产品id
        $proId = Request::param('id');
        $product = new ProductModel();
        if ($product->destroy($proId)) {
            return ['res'=>1,'msg'=>'删除成功!'];
        }
    }


}


Correcting teacher:天蓬老师Correction time:2019-05-14 17:48:48
Teacher's summary:凡是在方法中使用: $product = new ProductModel();, 其实都是不太友好的编程, 可以考虑放在参数中传入, 岂不更妙

Release Notes

Popular Entries