8、Hyperf 3 快速使用 - Hypref 3 数据库操作

作者: 温新

分类: 【Hyperf 3 基础系列】

阅读: 416

时间: 2023-04-25 12:19:16

hi,我是温新,一名 PHPer

Hypref 版本:Hyperf 3.0

说明:这是一个基础系列,有些文章有承上启下的作用。

学习目标:掌握数据库操作

本篇文章将学习 hyperf 操作数据库。基础操作这里就不再啰嗦了。文章中使用模型映射来操作数据库。

第一步:创建控制器

<?php
// App\Controller\home\UserController.php
    
namespace App\Controller\home;

use App\Model\User;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\GetMapping;
use Hyperf\View\RenderInterface;


#[Controller]
class UserController
{
    #[GetMapping('index')]
    public function index(RenderInterface $render)
    {
        $users = User::paginate();

        return $render->render('home.users.index', compact('users'));
    }

    #[GetMapping('show/{id}')]
    public function show(int $id)
    {
        return User::find($id);
    }
}

第二步:创建视图

// storage/view/home/users/index.php
<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    @foreach($users as $user)
        <ul>
            <li>{{ $user->name }} -- <a href="/home/user/show/{{$user->id}}">详情</a></li>
        </ul>
    @endforeach
</body>
</html>

第三步:运行浏览器运行

http://localhost:9501/home/user/index

关于模型中具体查询方法这里就不演示了。

请登录后再评论