hyperf: 访问数据库

一,配置数据库

.env中数据库的配置:

DB_DRIVER=mysql
DB_HOST=localhost
DB_PORT=3306
DB_DATABASE=mybase
DB_USERNAME=root
DB_PASSWORD=mypassword
DB_CHARSET=utf8mb4
DB_COLLATION=utf8mb4_unicode_ci
DB_PREFIX=

把host/port/base/username/password替换为自己实际环境中的配置

二,创建model

Model/ImageModel.php

<?php

namespace App\Model;

use Hyperf\DbConnection\Db;

class ImageModel
{
    protected string $table = 'news';

    //查询一条记录
    public function GetOneRowById($id) {
        $row = Db::table($this->table)->where('news_id', $id)->first(); // sql 会自动加上 limit 1
        if (is_null($row)) {
            return $row;
        } else {
            return object_to_array($row);
        }
    }

    //查询多条记录
    public function GetRowsByPage($userId,$offset,$limit) {
        $rows = Db::table($this->table)->where('user_id', $userId)->orderBy('news_id', 'desc')->offset($offset)->limit($limit)->get();
        return $rows;
    }
}

三,调用model类

controller/ImageController.php

    //查询详情
    public function imagedetail(RequestInterface $request, ResponseInterface $response) {

        $id = 3;
        $model = new ImageModel();
        $row = $model->GetOneRowById($id);

        if (is_null($row)) {
            $msg = "数据不存在";
        } else {
            $msg = $row['title'];
        }

        $data = [
            'row' => $msg,
        ];
        return $response->json($data);

    }

    //查询列表
    public function listimage(RequestInterface $request, ResponseInterface $response) {
        $model = new ImageModel();
        $userId = 0;
        $offset = 3;
        $limit = 2;
        $rows = $model->GetRowsByPage($userId,$offset,$limit);

        $data = [
            'rows' => $rows,
        ];
        return $response->json($data);
    }

四,测试效果:

posted @   刘宏缔的架构森林  阅读(8)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
历史上的今天:
2023-02-15 thinkphp:允许接口跨域访问(thinkphp v6.0.12LTS)
点击右上角即可分享
微信分享提示