博客列表 >模型实现查询和软删除+恢复--2018年05月27日

模型实现查询和软删除+恢复--2018年05月27日

植树青年小江同志的博客
植树青年小江同志的博客原创
2018年05月28日 00:24:14598浏览

实例

<?php

namespace app\index\controller;

use think\Controller;

use app\index\model\Staff as StaffModel;

use think\mode\concern\softDelete;


class Closure extends Controller
{

    public function read()
    {
        // 闭包查询

        $id = $this->request->param('staff_id') ? : 5;
        $staff = StaffModel::all(function ($query) {
            $query->where('staff_id', '>', $id);
        });

        dump($staff);
    }



    /**
     * 保存更新的资源
     *
     * @param  \think\Request  $request
     * @param  int  $id
     * @return \think\Response
     */
    public function update(Request $request)
    {
        //更新
        StaffModel::update(
            ['salary' => \think\Db::raw('salary=0')],

            function ($query) {
                $query->where('name', '李小璐');
            }
        );
    }

    /**
     * 删除指定资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function delete($id)
    {
        // 删除数据
        StaffModel::destroy(function ($query) {
            $query->where('name', '贾乃亮');
        });
    }

    public function create()
    {
        // 增加数据
        $data = [
            'name' => '贾乃亮',
            'sex' => 0,
            'age' => 33,
            'salary' => 91,
        ];

        $filed = ['name', 'sex', 'age', 'salary'];

        StaffModel::create($data, $field);
    }

    public function softDelete() {

        // 软删除和恢复操作

        // StaffModel::destroy(function ($query) {
        //     $query->where('salary', '<', 1000);
        // });
        
        StaffModel::destroy(37);
        $staff = StaffModel::withTrashed()->select();

        dump($staff);

        echo '<br>';
        $res = StaffModel::onlyTrashed()->select();

        foreach($res as $data) {
            $data->restore();
        }

        
    }
}

运行实例 »

点击 "运行实例" 按钮查看在线实例


声明:本文内容转载自脚本之家,由网友自发贡献,版权归原作者所有,如您发现涉嫌抄袭侵权,请联系admin@php.cn 核实处理。
全部评论
文明上网理性发言,请遵守新闻评论服务协议