模型基类常用方法

模型基类

find()->toArray();
        } catch (DataNotFoundException|ModelNotFoundException|DbException $e) {
            return [];
        }
    }
    /**
     * 获取单个字段
     * @param $fileName
     * @param $map
     * @return string
     */
    public function getFiled($fileName, $map): string
    {
        $row = self::where($map)->field($fileName)->find();
        if ($row) {
            return $row[$fileName];
        } else {
            return "";
        }
    }
    /**
     * 添加新记录
     * @param $data
     * @return mixed
     */
    public function addOne($data){
        $obj = self::create($data);
//        print_r($obj);exit();
        return $obj->id;
    }

    /**
     * 软删除记录
     * @param $id
     * @return bool
     */
    public function softDel($id): bool
    {
        $update = self::update(["isdel"=>1],["id"=>$id]);
        return $update->isdel==1;
    }

    /**
     * 更新一条数据
     * @param $data
     * @return bool
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function editOne($data): bool
    {
        $id = $data['id'];
        unset($data['id']);
        $obj = self::find($id);
        if($obj){
            $rst = $obj->save($data);
            return $rst !== false;
        }else{
            return false;
        }

    }
}

模型继承基类

最后控制器调用

getOne(1);
        print_r($row);
    }
    // 编辑
    public function edit(){
        $obj = new Workers();
        $data = ["id"=>15,"tel"=>'15821758130'];
        $rst = $obj->editOne($data);
        dump($rst);
//        print_r($rst);
    }
    // 添加
    public function add()
    {
        $obj = new Workers();
        $data = [
            "tel" => '17xxxxxx39',
            "password" => "123123",
            "photo" => "https://res.chengjingvet.com/2022052511021195430-4.jpg",
            "dname" => "司马医生",
            "level" => 1,
            "login_ip" => '127.0.0.1',
            "num" => 1
        ];
        $lastid = $obj->addOne($data);
        echo $lastid;
    }
    // 删除
    public function del(){
        $obj = new Workers();
        $result = $obj->softDel(15);
        if($result){
            echo '删除成功';
        }else{
            echo '删除失败';
        }
    }
}

你可能感兴趣的:(模型基类常用方法)