Hyperf 初体验-数据库

2019-12-18 11:45:36 浏览数 (1)

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

仔细阅读文档

仔细阅读文档

仔细阅读文档

重要的是说三遍!!!

创建数据连接

Hyperf 数据库的连接配置在 configautoloaddatabase.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
创建表结构
代码语言:javascript复制
<?php

use HyperfDatabaseSchemaSchema;
use HyperfDatabaseSchemaBlueprint;
use HyperfDatabaseMigrationsMigration;

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

创建模型

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

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

代码语言:javascript复制
<?php

declare (strict_types=1);
namespace AppModel;

use HyperfDbConnectionModelModel;
/**
 */
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 AppController;

use AppModelUser;
use HyperfHttpServerAnnotationAutoController;

/**
 * @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

0 人点赞