美文网首页
hf3.0 Db::查询时 将stdClass结果转为数组格式

hf3.0 Db::查询时 将stdClass结果转为数组格式

作者: geeooooz | 来源:发表于2023-07-18 16:08 被阅读0次

在某些场景下,您可能会希望查询出来的结果内采用 数组(Array) 而不是 stdClass 对象结构时,而 Eloquent 又去除了通过配置的形式配置默认的 FetchMode,那么此时可以通过监听器来监听 Hyperf\Database\Events\StatementPrepared 事件来变更该配置:

<?php
declare(strict_types=1);

namespace App\Listener;

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

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

    public function process(object $event) : void
    {
        if ($event instanceof StatementPrepared) {
            $event->statement->setFetchMode(PDO::FETCH_ASSOC);
        }
    }
}

相关文章

网友评论

      本文标题:hf3.0 Db::查询时 将stdClass结果转为数组格式

      本文链接:https://www.haomeiwen.com/subject/ulniudtx.html