前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Hyperf 初体验-数据库

Hyperf 初体验-数据库

作者头像
hedeqiang
发布2019-12-18 11:45:36
2.3K0
发布2019-12-18 11:45:36
举报
文章被收录于专栏:LaravelCodeLaravelCode

本节和数据库进行一次访问,包括数据库迁移、增删改查等操作

仔细阅读文档

仔细阅读文档

仔细阅读文档

重要的是说三遍!!!

创建数据连接

Hyperf 数据库的连接配置在 config\autoload\database.php 文件中

代码语言:javascript
复制
<?php

declare(strict_types=1);
/**
 * This file is part of Hyperf.
 *
 * @link     https://www.hyperf.io
 * @document https://doc.hyperf.io
 * @contact  group@hyperf.io
 * @license  https://github.com/hyperf-cloud/hyperf/blob/master/LICENSE
 */

return [
    'default' => [
        'driver' => env('DB_DRIVER', 'mysql'),
        'host' => env('DB_HOST', 'localhost'),
        'database' => env('DB_DATABASE', 'hyperf'),
        'port' => env('DB_PORT', 3306),
        'username' => env('DB_USERNAME', 'root'),
        'password' => env('DB_PASSWORD', ''),
        'charset' => env('DB_CHARSET', 'utf8'),
        'collation' => env('DB_COLLATION', 'utf8_unicode_ci'),
        'prefix' => env('DB_PREFIX', ''),
        'pool' => [
            'min_connections' => 1,
            'max_connections' => 10,
            'connect_timeout' => 10.0,
            'wait_timeout' => 3.0,
            'heartbeat' => -1,
            'max_idle_time' => (float) env('DB_MAX_IDLE_TIME', 60),
        ],
        'commands' => [
            'db:model' => [
                'path' => 'app/Model',
                'force_casts' => true,
                'inheritance' => 'Model',
            ],
        ],
    ],
];

其实默认情况下,不需要关系这个文件,配置 .env 文件就可以了。

编辑 .env 文件。修改 MySQL 信息

代码语言:javascript
复制
APP_NAME=skeleton

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

REDIS_HOST=localhost
REDIS_AUTH=
REDIS_PORT=6379
REDIS_DB=0

执行数据库迁移

代码语言:javascript
复制
php bin/hyperf.php gen:migration create_users_table
file
file
创建表结构
代码语言:javascript
复制
<?php

use Hyperf\Database\Schema\Schema;
use Hyperf\Database\Schema\Blueprint;
use Hyperf\Database\Migrations\Migration;

class CreateUsersTable extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::create('users', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('name');
            $table->string('password');
            $table->string('phone');
            $table->integer('status');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::dropIfExists('users');
    }
}

执行迁移命令

代码语言:javascript
复制
php bin/hyperf.php migrate
file
file

创建模型

代码语言:javascript
复制
php bin/hyperf.php db:model user
file
file

注意 1.1 版本以后创建模型命令发生变化。改为 gen:model

代码语言:javascript
复制
<?php

declare (strict_types=1);
namespace App\Model;

use Hyperf\DbConnection\Model\Model;
/**
 */
class User extends Model
{
    /**
     * The table associated with the model.
     *
     * @var string
     */
    protected $table = 'users';
    /**
     * The connection name for the model.
     *
     * @var string
     */
    protected $connection = 'default';
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name','phone','password','status'
    ];
    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [];
}

关于模型的更多用法请参考 文档 https://doc.hyperf.io/#/zh/db/model

简单增删改查
代码语言:javascript
复制
<?php

namespace App\Controller;

use App\Model\User;
use Hyperf\HttpServer\Annotation\AutoController;

/**
 * @AutoController()
 */
class IndexController extends Controller
{

    public function index()
    {
        return User::all();
    }

    public function create()
    {
        $user = new User();
        $user->name = 'Hyperf';
        $user->password = '123456';
        $user->status = 0;
        $user->phone = '15882888888';
        $user->save();
        // 0R
        $data = [
            'name' => 'hedeqiang',
            'phone' => '15555555555',
            'status' => 0,
            'password' => '123456',
        ];
        $user->fill($data);
        return $user->save();
    }

    public function update()
    {
        $user = User::query()->find(1);
        $user->name = 'Hi Hyperf';
        return $user->save();
    }

    public function show()
    {
        $user = User::query()->find(1);
        return $user;
    }

    public function delete()
    {
        $user = User::query()->find(1);
        return $user->delete();
    }
}

关于数据库操作 Hyperf 文档写的非常非常详细,里面包含了大量的例子。需要的时候直接看文档就好,这里只是简单测试下 https://doc.hyperf.io/#/zh/db/quick-start

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 创建数据连接
  • 执行数据库迁移
    • 创建表结构
    • 创建模型
      • 简单增删改查
      相关产品与服务
      数据库
      云数据库为企业提供了完善的关系型数据库、非关系型数据库、分析型数据库和数据库生态工具。您可以通过产品选择和组合搭建,轻松实现高可靠、高可用性、高性能等数据库需求。云数据库服务也可大幅减少您的运维工作量,更专注于业务发展,让企业一站式享受数据上云及分布式架构的技术红利!
      领券
      问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档