五 Hyperf 数据库操作

580 阅读1分钟

一 将查询结果转为数组

创建文件App\Listener\FetchModeListener.php

<?php

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

use Hyperf\Database\Events\QueryExecuted;
use Hyperf\Database\Events\StatementPrepared;
use Hyperf\Event\Annotation\Listener;
use Hyperf\Event\Contract\ListenerInterface;

#[Listener]
class FetchModeListener implements ListenerInterface
{
    public function listen(): array
    {
        return [
            StatementPrepared::class,
        ];
    }

    /**
     * @param QueryExecuted $event
     */
    public function process(object $event): void
    {
        if ($event instanceof StatementPrepared) {
            $event->statement->setFetchMode(\PDO::FETCH_ASSOC);
        }
    }
}

二 insert ,update

           $applyData = [
                'mobile' => $mobile,
                'org_name' => $org_name,
                "contact" => $contact,
                "remark" => $remark,
                "status" => Enum::APPLY_STATUS_PENDING,
                "created_at" => time(),
                "updated_at" => time(),
            ];
            $apply_id = Db::table('apply')->insertGetId( $applyData );


 Db::table('apply')->where('id', $apply_id)->update(['status' => Enum::APPLY_STATUS_OK]);

多个条件 。
where([
    ['status', '=', '1'],
    ['gender', '=', '1'],
])

三 常用查询(单行,多行,单个字段)

//单行
$demo_row  = Db::table('demo')->where('id', 1)->first();
//多行
$demo_rows = Db::table('demo')->select(['id', 'tname as title'])->get();
//单个字段
$demo_name = Db::table('demo')->where('id', 1)->pluck('tname');

四 直接sql

#有时候查询条件复杂,跨多表, 又不存在mysql oracle 的切换场景,直接sql才是best 	 practise.
//查询多行。
$table = env("DB_PREFIX", "")."user";
$sql = sprintf("select * from %s where id >0", $table);
$users = Db::select($sql);  //  返回array

//查询单行。
$sql = sprintf("select * from %s where id =1", $table);
$user = Db::selectOne($sql);  //  返回array

五 其它用法

//更新json 字段
Db::table('demo')->where('id', 1)->update(['content->tname' => time()]);

六 事务

Db::beginTransaction();
try{
    //code here
    Db::commit();
} catch(\Throwable $ex){
    return $this->code(ErrorCode::ERROR, ["ex" => $ex->getMessage()]);
    Db::rollBack();
}