Hyperf2.1版本将查询构造器查询的结果由对象格式转成数组格式
swoole  /  管理员 发布于 1年前   1914
官方手册描述:
将结果转为数组格式
在某些场景下,您可能会希望查询出来的结果内采用 数组(Array) 而不是 stdClass 对象结构时,而 Eloquent 又去除了通过配置的形式配置默认的 FetchMode,那么此时可以通过监听器来监听 Hyperf\Database\Events\StatementPrepared 事件来变更该配置
主要的效果就是链式操作get(), first() 等等...直接就是输出数组了 不用在toArray()了
配置步骤
在app/Listener/目录下新建文件 FetchModeListener.php
<?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)
{
if ($event instanceof StatementPrepared) {
$event->statement->setFetchMode(PDO::FETCH_ASSOC);
}
}
}
在把上面的信息复制上去就ok了
看看效果:
直接在登录接口上测试一下
<?php
declare(strict_types=1);
namespace App\Controller;
use Hyperf\View\RenderInterface;
use Hyperf\DbConnection\Db;
class UserController extends AbstractController
{
public function login(RenderInterface $render)
{
if ($this->request->isMethod('post')) {
$email = $this->request->input('email');
$password = md5($this->request->input('password'));
$res = Db::table('user')->where('email',$email)->where('password',$password)->first();
return $res;
}
}
}
看图
hyperf手册:https://hyperf.wiki/2.1/#/zh-cn/db/querybuilder
博主 在
2023年国务院办公厅春节放假通知:1月21日起休7天中评论 @ xiaoB 你只管努力,剩下的叫给天意;天若有情天亦老,..xiaoB 在
2023年国务院办公厅春节放假通知:1月21日起休7天中评论 会不会春节放假后又阳一次?..BUG4 在
你翻墙过吗?国内使用vpn翻墙可能会被网警抓,你需了解的事中评论 不是吧?..博主 在
go语言+beego框架中获取get,post请求的所有参数中评论 @ t1 直接在router.go文件中配就ok..Jade 在
如何在MySQL查询中获得当月记录中评论 Dear zongscan.com team, We can skyroc..
Copyright·© 2019 侯体宗版权所有·
粤ICP备20027696号