Hyperf 初体验-数据库

作者: hedeqiang

发布时间: 2019-09-30 11:42:27

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

仔细阅读文档

仔细阅读文档

仔细阅读文档

重要的是说三遍!!!

创建数据连接

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

<?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 信息

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

执行数据库迁移

php bin/hyperf.php gen:migration create_users_table

file

创建表结构

<?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');
    }
}

执行迁移命令

php bin/hyperf.php migrate

file

创建模型

php bin/hyperf.php db:model user

file

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

<?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

简单增删改查

<?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

关于极客返利

极客返利 是由我个人开发的一款网课返利、返现平台。包含 极客时间返现、拉勾教育返现、掘金小册返现、GitChat返现。目前仅包含这几个平台。后续如果有需要可以考虑其他平台。 简而言之就是:你买课,我返现。让你花更少的钱,就可以买到课程。

https://geek.laravelcode.cn

https://geek.idaka.ink

版权许可

本作品采用 知识共享署名 4.0 国际许可协议 进行许可。

转载无需与我联系,但须注明出处,注明文章来源 Hyperf 初体验-数据库