在某些場(chǎng)景下还最,您可能會(huì)希望查詢出來(lái)的結(jié)果內(nèi)采用 數(shù)組(Array) 而不是 stdClass 對(duì)象結(jié)構(gòu)時(shí),而 Eloquent 又去除了通過(guò)配置的形式配置默認(rèn)的 FetchMode毡惜,那么此時(shí)可以通過(guò)監(jiān)聽器來(lái)監(jiān)聽 Hyperf\Database\Events\StatementPrepared 事件來(lái)變更該配置:
<?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);
}
}
}